package com.bbcare.followup.plat.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

import javax.annotation.Resource;

import com.bbcare.followup.plat.store.ibatis.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.exceptions.JedisConnectionException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.SeqUtil;
import com.bbcare.comm.ToolUtils;
import com.bbcare.department.plat.entity.Doctor;
import com.bbcare.department.plat.service.IDoctorManagerService;
import com.bbcare.department.plat.store.ibatis.IDoctorDao;
import com.bbcare.followup.plat.entity.BsEvaluationStandard;
import com.bbcare.followup.plat.entity.EltDstRecored;
import com.bbcare.followup.plat.entity.FuAssessMentPosition;
import com.bbcare.followup.plat.entity.Patient;
import com.bbcare.followup.plat.entity.PatientContentData;
import com.bbcare.followup.plat.entity.PatientQueueScheme;
import com.bbcare.followup.plat.entity.PtEvaluationGuide;
import com.bbcare.followup.plat.entity.PtEvaluationResult;
import com.bbcare.followup.plat.service.IEvaluationWorkOrderService;
import com.bbcare.followup.plat.service.IFamilyReportService;
import com.bbcare.followup.plat.service.IFollowEvaluationService;
import com.bbcare.followup.plat.service.IFollowQueueService;
import com.bbcare.treat.plat.entity.PtArchiveData;
import com.bbcare.treat.plat.store.ibatis.IPtArchiveDataDAO;

/**
 *
 * @name: FollowEvaluationService.java
 * @author: tao
 * @createTime: 2017年6月20日
 * @description: 随访评测sevice服务实现类 基本业务逻辑代码复制1.0 暂无改动
 * @modify:
 *
 */
@Service
public class FollowEvaluationService implements IFollowEvaluationService {
	private final Log logger = LogFactory.getLog(FollowEvaluationService.class);

	@Resource(name = "jedisPool")
	private JedisPool jedisPool;

	@Autowired
	IFollowEvaluationDAO followEvaluationDao;

	@Autowired
	private IDoctorDao doctorDao;

	@Autowired
    private IFollowQueueService fllowQueueService;

	@Autowired
	IPatientDAO patientdao;

	@Autowired
    private IPatientTaskContentDAO PatientContentDao;

	@Autowired
    private IPtArchiveDataDAO PtArchiveDataDAO;


	@Autowired
	IEvaluationWorkOrderService evaluationWorkOrderService;

	@Autowired
	IFamilyReportService familyReportService;

	@Autowired
    private IEvaluationWorkOrderDAO evaluationWorkOrderDAO;

	@Autowired
	private IDoctorManagerService doctorManagerService;

	@Autowired
	IFamilyReportDAO familyReportDAO;

	@Autowired
	IEltDstRecoreDAO iEltDstRecoreDAO;

	@Autowired
	IPatientQueueSchemeDAO iPatientQueueSchemeDao;

	@Autowired
	ICommonDao iCommonDao;

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> getBaileyScreeningPostion() throws Exception {
		Jedis jedis = null;
		String monthForAge;
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION_1);

			Map<String, Object> postions = new HashMap<String, Object>();
			// 获取考卷总共题数
//			Object a = jedis.hgetAll("Postion");
			getPostion(jedis);
			int num = Integer.parseInt(jedis.hmget("Postion", "BaileyScreening").get(0));
			for (int i = 1; i <= num; i++) {
				String key = "BaileyScreening_" + i;
				// 每个项目的题目
				//Map<String, Object> projectMap = new TreeMap<>();
                Map<String, Object> projectMap = new HashMap<>();
				// 每个项目的时间中题目
				List<Map<String, String>> timeMap = new ArrayList<Map<String, String>>();
				// 每个题目的ID，问题
				//Map<String, String> postionMap = new TreeMap<String, String>();
                Map<String, String> postionMap = new HashMap<>();
				// 取出每一个题目内容

				Map<String, Object> map = null;
				if (jedis.hmget("Postion", key).get(0) != null) {
					map = ToolUtils.stringToMap(jedis.hmget("Postion", key).get(0));
					String project = "";
					if (map.get("project").equals("认知能力"))
						project = "cognitive";
					if (map.get("project").equals("语言理解"))
						project = "understand";
					if (map.get("project").equals("语言表达"))
						project = "express";
					if (map.get("project").equals("精细动作"))
						project = "fineMotor";
					if (map.get("project").equals("大动作"))
						project = "bigAction";
					postionMap.put("id", i + "");
					postionMap.put("name", map.get("name") + "");
					if (postions.get(project) != null) {
						projectMap = (Map<String, Object>) postions.get(project);
						if (projectMap.get(map.get("monthForAge")) != null) {
							timeMap = (ArrayList<Map<String, String>>) projectMap.get(map.get("monthForAge"));
						}
					}
					timeMap.add(postionMap);
					projectMap.put(map.get("monthForAge") + "", timeMap);
					if (project.equals("express") && null != projectMap.get("B")) {
                        ArrayList<Map<String, String>> bList    = (ArrayList<Map<String, String>>)projectMap.get("B");
                        ArrayList<Map<String, String>> aList    = new ArrayList<Map<String, String>>();
                        for(Map<String, String> bMap : bList)   {
                            aList.add(new HashMap<>(bMap));
                        }
                        projectMap.put("A", aList);
                    }
					postions.put(project, projectMap);
				}
			}
			return postions;
		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(
							ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,
							"Redis缓存关闭失败!"));
				}
			}
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> getNeuropsychologyPostion() throws Exception {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION_1);

			Map<String, Object> postions = new TreeMap<String, Object>();
			// 获取考卷总共题数
			getPostion(jedis);
			int num = Integer.parseInt(jedis.hmget("Postion", "Neuropsychology").get(0));
			for (int i = 1; i <= num; i++) {
				String key = "Neuropsychology_" + i;
				// 每个月份的题目
				Map<String, Object> monthMap = new HashMap<>();
				// 每个月份的具体项目中题目
				ArrayList<Map<String, String>> projectMap = new ArrayList<Map<String, String>>();
				// 每个题目的ID，问题
				Map<String, String> postionMap = new HashMap<String, String>();
				// 取出每一个题目内容
				Map<String, Object> map = ToolUtils.stringToMap(jedis.hmget("Postion", key).get(0));
				String project = "";
				if (map.get("project").equals("大运动")) {
					project = "bigMovement";
				}else if (map.get("project").equals("精细动作")) {
					project = "fineAction";
				}else if (map.get("project").equals("适应能力")) {
					project = "adaptability";
				}else if (map.get("project").equals("语言")) {
					project = "language";
				}else if (map.get("project").equals("社交行为")) {
					project = "socialBehavior";
				}
				postionMap.put("id", i + "");
				postionMap.put("name", map.get("name") + "");

				if (map.get("monthForAge") != null) {
					// 如果存在相同月份就获取之前的数据
					if (postions.get(map.get("monthForAge")) != null) {
						monthMap = (Map<String, Object>) postions.get(map.get("monthForAge"));
						// 如果在相同月份存在相同项目就获取之前的数据
						if (monthMap.get(project) != null) {
							projectMap = (ArrayList<Map<String, String>>) monthMap.get(project);
						}
					}
				}
				projectMap.add(postionMap);
				monthMap.put(project, projectMap);
				postions.put(map.get("monthForAge") + "", monthMap);
			}
			return postions;
		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}

	@Override
	public void getPostion(Jedis jedis) throws Exception {


			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION_1);
			//不存在从数据库获取
			Map map = new HashMap();
			if(!jedis.exists("Postion")){
				List<LinkedHashMap<String, Object>> list = iCommonDao.select(" select `key`,`value` from scale_postion where type = 1 ");
				list.forEach(i->{
				  map.put(i.get("key"),i.get("value"));
				});
				jedis.hmset("Postion",map);
			};
				map.clear();
			if(!jedis.exists("ExaminationPaper")){
				List<LinkedHashMap<String, Object>> list = iCommonDao.select(" select `key`,`value` from scale_postion where type = 2 ");
				list.forEach(i->{
					map.put(i.get("key"),i.get("value"));
				});
				jedis.hmset("ExaminationPaper",map);
			}



	}
	@Override
	public Map<String, Object> getBaileyScreeningGuide(Date date)
			throws Exception {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION_1);
			Map<String, Object> score = new HashMap<String, Object>();
			int day = DateUtil.daysBetween(date, new Date());
			String guide = "<ul class='clearfix'><h2>暂缺该年龄的指导意见！</h2></ul>";

			if (20 < day && day <= 90)
				guide = jedis.hget("guide:BaileyScreening", "29-60");
			if (90 < day && day <= 120)
				guide = jedis.hget("guide:BaileyScreening", "90-120");
			if (120 < day && day <= 150)
				guide = jedis.hget("guide:BaileyScreening", "120-150");
			if (150 < day && day <= 180)
				guide = jedis.hget("guide:BaileyScreening", "150-180");
			if (180 < day && day <= 210)
				guide = jedis.hget("guide:BaileyScreening", "180-210");
			if (210 < day && day <= 270)
				guide = jedis.hget("guide:BaileyScreening", "210-270");
			if (270 < day && day <= 330)
				guide = jedis.hget("guide:BaileyScreening", "270-330");
			if (330 < day && day <= 390)
				guide = jedis.hget("guide:BaileyScreening", "330-390");
			if (390 < day && day <= 480)
				guide = jedis.hget("guide:BaileyScreening", "390-480");
			if (480 < day && day <= 570)
				guide = jedis.hget("guide:BaileyScreening", "480-570");
			score.put("guide", guide);
			return score;

		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> getGesellPostion() throws Exception {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION_1);
			Map<String, Object> postions = new TreeMap<>();
			getPostion(jedis);
			// 获取考卷总共题数
			int num = Integer.parseInt(jedis.hmget("Postion", "Gesell").get(0));
			for (int i = 0; i < num; i++) {
				String key = "Gesell_" + i;
				// 每个月份的题目
				Map<String, Object> monthMap = new HashMap<>();
				// 每个月份的具体项目中题目
				ArrayList<Map<String, String>> projectMap = new ArrayList<Map<String, String>>();
				// 每个题目的ID，问题
				Map<String, String> postionMap = new HashMap<String, String>();
				// 取出每一个题目内容
				Map<String, Object> map = ToolUtils.stringToMap(jedis.hmget("Postion", key).get(0));
				String project = "";
				if (map.get("project").equals("大运动"))
					project = "bigMovement";
				if (map.get("project").equals("精细动作"))
					project = "fineAction";
				if (map.get("project").equals("适应性"))
					project = "adaptability";
				if (map.get("project").equals("语言"))
					project = "language";
				if (map.get("project").equals("个人——社会"))
					project = "socialBehavior";
				postionMap.put("id", i + "");
				postionMap.put("name", map.get("name") + "");
				if (map.get("monthForAge") != null) {
					// 如果存在相同月份就获取之前的数据
					if (postions.get(map.get("monthForAge")) != null) {
						monthMap = (Map<String, Object>) postions.get(map.get("monthForAge"));
						// 如果在相同月份存在相同项目就获取之前的数据
						if (monthMap.get(project) != null) {
							projectMap = (ArrayList<Map<String, String>>) monthMap.get(project);
						}
					}
				}
				projectMap.add(postionMap);
				monthMap.put(project, projectMap);
				postions.put(map.get("monthForAge") + "", monthMap);
			}
			return postions;

		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}

	@Override
	public Map<String, Object> getTemperamentPostion(Patient patient,String createTime1)
			throws Exception {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION_1);
			Map<String, Object> postions = new LinkedHashMap<String, Object>();
			boolean isChild = true; // 该年龄段是否存在气质问题
			String key = "Temperament_1_4";
			getPostion(jedis);
			// 传入答题 结果
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");// 小写的mm表示的是分钟
			boolean flag = false;// 是否早产.默认非早产儿
			String birthday = patient.getBirthday();
			if (null == birthday) {
				throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_BIRTHDAY_NOT_EXIST, "用户没有出生日期");
			}
			Date date = new Date();
			String createTime = sdf.format(date);// 评估时间
			if(!StringUtils.isEmpty(createTime1)) {
				createTime = createTime1;
			}
			String expectedDay = patient.getExpectedDay();
			// 预产期，是否有预产期，如果没有默认是非早产儿
			// 如果有预产期，判断是否早产
			int mouth = 0;// 月数
			int day = 0;// 天数
			if (null != expectedDay) {
				// 比较两个时间的大小
				int bigOne = ToolUtils.calPrenDayByBirthAndExpect(birthday, expectedDay);
				Date date1 = sdf.parse(expectedDay);
				Date date2 = sdf.parse(birthday);
				Date date3 = sdf.parse(createTime);// 评估时间
				// 计算两个时间差(评估时用户年龄)
				int ages = DateUtil.daysBetween(date2, date3);
				int ageMouth = ages / 30;

				// 如果预产期大于出生日期 孕周小于37周，显示为早产,并计算出时间差
				if (bigOne < 260 && ageMouth < 31) {
					int expect = DateUtil.daysBetween(date2, date1);
					flag = true;
					mouth = expect / 30;
					day = expect % 30;
				}
			}
			// 计算月龄
			int day3 = 0;// 天
			int month3 = 0;// 月
			int year3 = 0;// 年
			Map<String, Object> map1 = new HashMap<String, Object>();
			map1.put("birthday", birthday);
			map1.put("createTime", createTime);
			// 调用计算组件
			Map<String, Object> mapOut = ToolUtils.CalculateAgeOfMoon(map1);
			if (mapOut != null && mapOut.size() > 0) {
				day3 = (int) mapOut.get("day3");
				month3 = (int) mapOut.get("month3");
				year3 = (int) mapOut.get("year3");
			}
			// 如果是早产儿，且年龄在24个月之内的儿童需要计算纠正年龄 flag=true 为早产儿
			// 用计算出来的月龄减去早产的时间获取纠正年龄
			if (flag) {
				if (day3 > day || day3 == day) {
					day3 = day3 - day;
				} else {
					if (month3 > mouth) {
						day3 = day3 + 30 - day;
						month3 = month3 - 1;
					} else {
						if (year3 > 0) {
							day3 = day3 + 30 - day;
							month3 = month3 + 12 - 1;
							year3 = year3 - 1;
						}
					}
				}
				if (month3 > mouth) {
					month3 = month3 - mouth;
				} else {
					if (year3 > 0) {
						month3 = month3 + 12 - mouth;
						year3 = year3 - 1;
					}
				}
			}
			// 计算最后的月龄
			int days = year3 * 365 + month3 * 30 + day3;
			int month = days % 30 > 15 ? days / 30 + 1 : days / 30;
			if (1 <= month && month <= 4) {
				key = "Temperament_1_4";
			} else if (4 < month && month < 12) {
				key = "Temperament_4_12";
			} else if (12 <= month && month < 36) {
				key = "Temperament_12_36";
			} else
				isChild = false;
			if (isChild) {
				List<String> lists = JSON.parseArray(jedis.hmget("ExaminationPaper", key).get(0),String.class);
				for (String list : lists) {
					// 取出每一个题目内容
					Map<String, Object> map = ToolUtils.stringToMap(jedis.hmget("Postion", key + "_" + list).get(0));
					postions.put(list, map.get("name"));
				}
			}else{
				throw new AppException("10000", "用户年龄超出测试范围！");
			}
			return postions;

		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}

	/**
	 * Name: 或取对应维度的得分 Params: dimension： 各维度中的标准 postions： 前端传递的结果
	 */
	public float getTemperamentDimensionScore(Map<String, Object> dimension,Map<String,Object> postions) {
		String[] reverseEntry = (String[]) dimension.get("reverseEntry"); // 反向条目中题目Id集合
		String[] positiveEntry = (String[]) dimension.get("positiveEntry"); // 正向条目中题目Id集合
		int entryNum = (int) dimension.get("entryNum"); // 该维度条目数
		float reverseScore = 0, positiveScore = 0; // 正/反向/维度得分
		String tempID; // 题目ID
		// 获取正、负向条目得分
		for (int i = 0; i < reverseEntry.length; i++) {
			Object tempScore;
			if (postions.get("0") == null)
				tempID = reverseEntry[i];
			else
				tempID = (Integer.parseInt(reverseEntry[i]) - 1) + "";// 由于word读数据原因，一些题目编号从0开始了，需-1
			tempScore = postions.get(tempID);
			if (tempScore != null)
				reverseScore += Float.parseFloat((String) tempScore);
		}
		reverseScore = 7 - reverseScore;
		for (int i = 0; i < positiveEntry.length; i++) {
			Object tempScore;
			if (postions.get("0") == null)
				tempID = positiveEntry[i];
			else
				tempID = (Integer.parseInt(positiveEntry[i]) - 1) + "";// 由于word读数据原因，一些题目编号从0开始了，需-1
			tempScore = postions.get(tempID);
			if (tempScore != null)
				positiveScore += Float.parseFloat((String) tempScore);
		}
		// 维度得分
		return (reverseScore + positiveScore) / entryNum;
	}

	/**
	 * Name: 创建评估标准 Params: month： 宝宝月龄
	 */
	public Map<String, Map<String, Object>> createTemperamentStandard(int month) {
		Map<String, Map<String, Object>> resultsMap = new LinkedHashMap<String, Map<String, Object>>();
		Map<String, Object> activityLevel = new LinkedHashMap<String, Object>(); // 活动水平
		Map<String, Object> rhythmic = new LinkedHashMap<String, Object>(); // 节律性
		Map<String, Object> dodge = new LinkedHashMap<String, Object>(); // 趋避性
		Map<String, Object> adaptive = new LinkedHashMap<String, Object>(); // 适应性
		Map<String, Object> intensityReaction = new LinkedHashMap<String, Object>(); // 反应强度
		Map<String, Object> mood = new LinkedHashMap<String, Object>(); // 心境
		Map<String, Object> persistence = new LinkedHashMap<String, Object>(); // 持久性
		Map<String, Object> attentionScattered = new LinkedHashMap<String, Object>(); // 注意分散
		Map<String, Object> reactionThreshold = new LinkedHashMap<String, Object>(); // 反应阈

		if (1 <= month && month <= 4) {
			// 活动水平：反向条目 1/10/28/62；正向条目19/37/46/55（条目数=8）
			activityLevel.put("reverseEntry", new String[] { "1", "10", "28","62" });
			activityLevel.put("positiveEntry", new String[] { "19", "37", "46","55" });
			activityLevel.put("entryNum", 8);
			// 节律性：反向条目 2/11/20/56/72；正向条目29/38//47/63/68（条目数=10）
			rhythmic.put("reverseEntry", new String[] { "2", "11", "20", "56","72" });
			rhythmic.put("positiveEntry", new String[] { "29", "38", "47","63", "68" });
			rhythmic.put("entryNum", 10);
			// 趋避性：反向条目48；正向条目3/12/21/30/39（条目数=6）
			dodge.put("reverseEntry", new String[] { "48" });
			dodge.put("positiveEntry", new String[] { "3", "12", "21", "30","39" });
			dodge.put("entryNum", 6);
			// 适应性：反向条目 4/22/31/57/73；正向条目13/40/49/64/69（条目数=10）
			adaptive.put("reverseEntry", new String[] { "4", "22", "31", "57","73" });
			adaptive.put("positiveEntry", new String[] { "13", "40", "49","64", "69" });
			adaptive.put("entryNum", 10);
			// 反应强度：反向条目 无 ；正向条目5/14/23/32/41/50（条目数=6）
			intensityReaction.put("reverseEntry", new String[] {});
			intensityReaction.put("positiveEntry", new String[] { "5", "14","23", "32", "41", "50" });
			intensityReaction.put("entryNum", 6);
			// 心境：反向条目15/51/65/70/74；正向条目6/24/33/42/58/76（条目数=11）
			mood.put("reverseEntry", new String[] { "15", "51", "65", "70","74" });
			mood.put("positiveEntry", new String[] { "6", "24", "33", "42","58", "76" });
			mood.put("entryNum", 11);
			// 持久性：反向条目7/16/25/34/43/52/66；正向条目59（条目数=8）
			persistence.put("reverseEntry", new String[] { "7", "16", "25","34", "43", "52", "66" });
			persistence.put("positiveEntry", new String[] { "59" });
			persistence.put("entryNum", 8);
			// 注意分散：反向条目35/44/53；正向条目8/17/26/60（条目数=7）
			attentionScattered.put("reverseEntry", new String[] { "35", "44","53" });
			attentionScattered.put("positiveEntry", new String[] { "8", "17","26", "60" });
			attentionScattered.put("entryNum", 7);
			// 反应阈：反向条目71；正向条目9/18/27/36/45/54/61/67/75（条目数=10）
			reactionThreshold.put("reverseEntry", new String[] { "71" });
			reactionThreshold.put("positiveEntry", new String[] { "9", "18","27", "36", "45", "54", "61", "67", "75" });
			reactionThreshold.put("entryNum", 10);

			if (1 <= month && month <= 2) {
				activityLevel.put("mean", 3.68f);
				activityLevel.put("s", 0.66f);
				rhythmic.put("mean", 3.64f);
				rhythmic.put("s", 0.66f);
				dodge.put("mean", 2.45f);
				dodge.put("s", 0.79f);
				adaptive.put("mean", 2.67f);
				adaptive.put("s", 0.62f);
				intensityReaction.put("mean", 3.80f);
				intensityReaction.put("s", 0.78f);
				mood.put("mean", 3.32f);
				mood.put("s", 0.56f);
				persistence.put("mean", 3.19f);
				persistence.put("s", 0.74f);
				attentionScattered.put("mean", 2.90f);
				attentionScattered.put("s", 0.72f);
				reactionThreshold.put("mean", 4.16f);
				reactionThreshold.put("s", 0.65f);
			} else {
				activityLevel.put("mean", 3.87f);
				activityLevel.put("s", 0.72f);
				rhythmic.put("mean", 3.41f);
				rhythmic.put("s", 0.66f);
				dodge.put("mean", 2.77f);
				dodge.put("s", 0.92f);
				adaptive.put("mean", 2.53f);
				adaptive.put("s", 0.64f);
				intensityReaction.put("mean", 3.75f);
				intensityReaction.put("s", 0.81f);
				mood.put("mean", 2.84f);
				mood.put("s", 0.61f);
				persistence.put("mean", 2.67f);
				persistence.put("s", 0.78f);
				attentionScattered.put("mean", 2.68f);
				attentionScattered.put("s", 0.82f);
				reactionThreshold.put("mean", 4.27f);
				reactionThreshold.put("s", 0.70f);
			}
		} else if (4 < month && month < 12) {
			// 活动水平：反向条目4/12/30/55/79/86；正向条目17/33/43/51/64/71/95（条目数=13）
			activityLevel.put("reverseEntry", new String[] { "4", "12", "30","55", "79", "86" });
			activityLevel.put("positiveEntry", new String[] { "17", "33", "43","51", "64", "71", "95" });
			activityLevel.put("entryNum", 13);
			// 节律性：反向条目 1/13/28/50/60/73/85；正向条目20/35/46/67/77（条目数=12）
			rhythmic.put("reverseEntry", new String[] { "1", "13", "28", "50","60", "73", "85" });
			rhythmic.put("positiveEntry", new String[] { "20", "35", "46","67", "77" });
			rhythmic.put("entryNum", 12);
			// 趋避性：反向条目5/24/45/62/82；正向条目14/31/36/66/74/91（条目数=11）
			dodge.put("reverseEntry", new String[] { "5", "24", "45", "62","82" });
			dodge.put("positiveEntry", new String[] { "14", "31", "36", "66","74", "91" });
			dodge.put("entryNum", 11);
			// 适应性：反向条目6/9/29/49/56/94；正向条目19/34/65/78/90（条目数=11）
			adaptive.put("reverseEntry", new String[] { "6", "9", "29", "49","56", "94" });
			adaptive.put("positiveEntry", new String[] { "19", "34", "65","78", "90" });
			adaptive.put("entryNum", 11);
			// 反应强度：反向条目 10/26/75/84/89；正向条目18/38/42/54/70（条目数=10）
			intensityReaction.put("reverseEntry", new String[] { "10", "26","75", "84", "89" });
			intensityReaction.put("positiveEntry", new String[] { "18", "38","42", "54", "70" });
			intensityReaction.put("entryNum", 10);
			// 心境：反向条目 23/27/39/61/63/81；正向条目2/48/76/93（条目数=10）
			mood.put("reverseEntry", new String[] { "23", "27", "39", "61","63", "81" });
			mood.put("positiveEntry", new String[] { "2", "48", "76", "93" });
			mood.put("entryNum", 10);
			// 持久性：反向条目 8/16/32/41/58；正向条目3/25/88（条目数=8）
			persistence.put("reverseEntry", new String[] { "8", "16", "32","41", "58" });
			persistence.put("positiveEntry", new String[] { "3", "25", "88" });
			persistence.put("entryNum", 8);
			// 注意分散：反向条目 7/21/44/53/59/80/87；正向条目15/40/68（条目数=10）
			attentionScattered.put("reverseEntry", new String[] { "7", "21","44", "53", "59", "80", "87" });
			attentionScattered.put("positiveEntry", new String[] { "15", "40","68" });
			attentionScattered.put("entryNum", 10);
			// 反应阈：反向条目 22/47/72/92；正向条目11/37/52/57/69/83（条目数=10）
			reactionThreshold.put("reverseEntry", new String[] { "22", "47","72", "92" });
			reactionThreshold.put("positiveEntry", new String[] { "11", "37","52", "57", "69", "83" });
			reactionThreshold.put("entryNum", 10);

			activityLevel.put("mean", 3.69f);
			activityLevel.put("s", 0.62f);
			rhythmic.put("mean", 3.09f);
			rhythmic.put("s", 0.70f);
			dodge.put("mean", 2.91f);
			dodge.put("s", 0.81f);
			adaptive.put("mean", 2.94f);
			adaptive.put("s", 0.69f);
			intensityReaction.put("mean", 3.59f);
			intensityReaction.put("s", 0.66f);
			mood.put("mean", 3.37f);
			mood.put("s", 0.70f);
			persistence.put("mean", 3.21f);
			persistence.put("s", 0.78f);
			attentionScattered.put("mean", 2.91f);
			attentionScattered.put("s", 0.66f);
			reactionThreshold.put("mean", 3.88f);
			reactionThreshold.put("s", 0.68f);
		} else if (12 <= month && month <= 36) {
			// 活动水平：反向条目12/18/64/73/85/90；正向条目2/24/36/47/52/58（条目数=12）
			activityLevel.put("reverseEntry", new String[] { "12", "18", "64","73", "85", "90" });
			activityLevel.put("positiveEntry", new String[] { "2", "24", "36","47", "52", "58" });
			activityLevel.put("entryNum", 12);
			// 节律性：反向条目 1/30/59/77/82；正向条目7/17/33/42/54/68（条目数=11）
			rhythmic.put("reverseEntry", new String[] { "1", "30", "59", "77","82" });
			rhythmic.put("positiveEntry", new String[] { "7", "17", "33", "42","54", "68" });
			rhythmic.put("entryNum", 11);
			// 趋避性：反向条目 5/21/26/38/45/57/76/96；正向条目9/53/87/94（条目数=12）
			dodge.put("reverseEntry", new String[] { "5", "21", "26", "38","45", "57", "76", "96" });
			dodge.put("positiveEntry", new String[] { "9", "53", "87", "94" });
			dodge.put("entryNum", 12);
			// 适应性：反向条目 11/32/56/60/65；正向条目44/78/88/93（条目数=9）
			adaptive.put("reverseEntry", new String[] { "11", "32", "56", "60","65" });
			adaptive.put("positiveEntry",new String[] { "44", "78", "88", "93" });
			adaptive.put("entryNum", 9);
			// 反应强度：反向条目 3/55/70；正向条目14/19/29/35/46/74/83（条目数=10）
			intensityReaction.put("reverseEntry", new String[] { "3", "55","70" });
			intensityReaction.put("positiveEntry", new String[] { "14", "19","29", "35", "46", "74", "83" });
			intensityReaction.put("entryNum", 10);
			// 心境：反向条目 4/31/43/63/75；正向条目8/20/25/49/69/84/89/95（条目数=13）
			mood.put("reverseEntry",new String[] { "4", "31", "43", "63", "75" });
			mood.put("positiveEntry", new String[] { "8", "20", "25", "49","69", "84", "89", "95" });
			mood.put("entryNum", 13);
			// 持久性：反向条目 15/28/62/71/79/91；正向条目6/34/40/51/86（条目数=11）
			persistence.put("reverseEntry", new String[] { "15", "28", "62","71", "79", "91" });
			persistence.put("positiveEntry", new String[] { "6", "34", "40","51", "86" });
			persistence.put("entryNum", 11);
			// 注意分散：反向条目 13/37/41/50/66；正向条目22/27/61/72/81/97（条目数=11）
			attentionScattered.put("reverseEntry", new String[] { "13", "37","41", "50", "66" });
			attentionScattered.put("positiveEntry", new String[] { "22", "27","61", "72", "81", "97" });
			attentionScattered.put("entryNum", 11);
			// 反应阈：反向条目 16/23/39/67/80/92；正向条目10/48（条目数=8）
			reactionThreshold.put("reverseEntry", new String[] { "16", "23","39", "67", "80", "92" });
			reactionThreshold.put("positiveEntry", new String[] { "10", "48" });
			reactionThreshold.put("entryNum", 8);

			activityLevel.put("mean", 3.66f);
			activityLevel.put("s", 0.59f);
			rhythmic.put("mean", 2.97f);
			rhythmic.put("s", 0.60f);
			dodge.put("mean", 3.32f);
			dodge.put("s", 0.82f);
			adaptive.put("mean", 3.34f);
			adaptive.put("s", 0.60f);
			intensityReaction.put("mean", 3.91f);
			intensityReaction.put("s", 0.68f);
			mood.put("mean", 3.07f);
			mood.put("s", 0.59f);
			persistence.put("mean", 3.17f);
			persistence.put("s", 0.71f);
			attentionScattered.put("mean", 3.33f);
			attentionScattered.put("s", 0.64f);
			reactionThreshold.put("mean", 2.02f);
			reactionThreshold.put("s", 0.76f);
		}

		resultsMap.put("activityLevel", activityLevel);
		resultsMap.put("rhythmic", rhythmic);
		resultsMap.put("dodge", dodge);
		resultsMap.put("adaptive", adaptive);
		resultsMap.put("intensityReaction", intensityReaction);
		resultsMap.put("mood", mood);
		resultsMap.put("persistence", persistence);
		resultsMap.put("attentionScattered", attentionScattered);
		resultsMap.put("reactionThreshold", reactionThreshold);
		return resultsMap;
	}

	@Override
	public Map<String, Object> getWechslerPostion(Date date) throws Exception {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION_1);

			Map<String, Object> postions = new LinkedHashMap<String, Object>();
			String type = "Small";
			int day = DateUtil.daysBetween(date, new Date());
			List<String> objects = Arrays.asList("常识", "动物房", "词汇", "图画补缺","算术题", "迷宫", "几何图形", "类同词", "木块图案", "理解");
			if (day > (6 * 365)) {
				type = "Big";
				objects = Arrays.asList("常识", "填图", "类同", "图片排列", "算术", "积木",
						"词汇", "拼图", "理解", "译码", "顺背1", "顺背2", "倒背1", "倒背2","迷津");
			}
			for (String object : objects) {
				List<String> lists = JSON.parseArray(jedis.hmget("ExaminationPaper",type + "Wechsler_" + type + "_" + object).get(0), String.class);
				Map<String, Object> postion = new TreeMap<String, Object>();
				for (String list : lists) {
					// 取出每一个题目内容
					Map<String, Object> map = ToolUtils.stringToMap(jedis.hmget("Postion", type + "Wechsler_" + list).get(0));
					Map<String, Object> temp = new LinkedHashMap<String, Object>();
					temp.put("name", map.get("name"));
					temp.put("score", map.get("score"));
					postion.put(list, temp);
				}
				postions.put(object, postion);
			}
			return postions;
		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}

	@Override
	@Transactional
	public int savePtEvaluationResult(PtEvaluationResult result,List<PtEvaluationGuide> list) throws Exception {
		//ASQ和养育环境 指导意见
		if(!CollectionUtils.isEmpty(list)){
			for(int i = 0 ;i<list.size();i++){
				list.get(i).setEvaluationId(result.getId());
			}
			followEvaluationDao.saveBatchPtEvaluationGuide(list);
		}
		int i = followEvaluationDao.savePtEvaluationResult(result);
		return i;
	}

	@Override
	public int selectPtEvaluationResultCount(Map<String, Object> map)
			throws Exception {
		int i = followEvaluationDao.countEvaluationResults(map);
		return i;
	}

	@Override
	public List<Map<String, Object>> selectPtEvaluationResults(
			Map<String, Object> paramMap) throws Exception {
		int page = (paramMap.get("page") != null && !StringUtils
				.isEmpty(paramMap.get("page").toString())) ? Integer.parseInt(paramMap.get("page").toString()) : 1;
		int rows = (paramMap.get("rows") != null && !StringUtils
				.isEmpty(paramMap.get("rows").toString())) ? Integer.parseInt(paramMap.get("rows").toString()) : 20;

		String sourseType= (String)paramMap.get("sourseType");
		if(Constants.SOURCE_TYPE_APP.equals(sourseType)){

		}else{
			paramMap.put("start", rows * (page - 1));
			paramMap.put("end", rows);
		}

		// paramMap.put("status","01");

		List<Map<String, Object>> list = followEvaluationDao.selectEvaluationResults(paramMap);
		Map<String, Object> map = null;
		if (!CollectionUtils.isEmpty(list)) {
			//一妇婴贝利多项目特殊处理
			if(!"0".equals((String)paramMap.get("showFlag"))) {
				for (int i = 0; i < list.size(); i++) {
					map = list.get(i);
					list.get(i).put("createTime",DateUtil.getTimeStampSec(map.get("createTime").toString()));
					if (null != map.get("pregnancyday")) {
						long pregnancyday = Long.parseLong(map.get("pregnancyday").toString());
						if (pregnancyday < 280) {
							list.get(i).put("userType", "01");// 早产儿
						} else {
							list.get(i).put("userType", "02");
						}
					}
					map = null;
				}
			}else {
				for (int i = 0; i < list.size(); i++) {
						map = list.get(i);
						list.get(i).put("createTime",DateUtil.getTimeStampSec(map.get("createTime").toString()));
						if (null != map.get("pregnancyday")) {
							long pregnancyday = Long.parseLong(map.get("pregnancyday").toString());
							if (pregnancyday < 280) {
								list.get(i).put("userType", "01");// 早产儿
							} else {
								list.get(i).put("userType", "02");
							}
						}

					List <PatientContentData> lists =  PatientContentDao.listCntDataByUserIdAndAcceptPrivate(map);
					if(!CollectionUtils.isEmpty(lists)) {
						for(int j = 0;j<lists.size();j++) {
							if(Constants.QUESTION_ID_FOR_WEIGHT.equals(lists.get(j).getQuestionId())) {
								list.get(i).put("weight",lists.get(j).getQuestionAnswer());
							}else if(Constants.QUESTION_ID_FOR_JIUZHENG.equals(lists.get(j).getQuestionId())) {
								list.get(i).put("correctAge",lists.get(j).getQuestionAnswer());
							}
						}
					}
					map = null;
				}
			}
		}
		return list;
	}

	@Override
	public List<Map<String, Object>> getEvaluationPatientList(
			Map<String, Object> paramMap) throws Exception {

			List<Map<String, Object>>  list = new ArrayList<Map<String, Object>>();
			String queueId  = ((paramMap.get("queueId")!=null && !StringUtils.isEmpty(paramMap.get("queueId").toString()))) ? paramMap.get("queueId").toString() : null;

			List<String> queueIdArray = new ArrayList<String>();
			if(StringUtils.isEmpty(queueId)){
				// 根据当前登录账号获取，其可以查看的队列id
				queueIdArray = fllowQueueService.getQueueArrByAuthority(paramMap);
				if(CollectionUtils.isEmpty(queueIdArray)){
					logger.warn("该账号无可查看到的患者信息...arg==" + paramMap.toString());
					return list;
				}
			}else{
				queueIdArray.add(queueId);
			}

	        paramMap.put("queueIdIn",queueIdArray);
	        paramMap.put("userStatus",Constants.QUEUE_STATUS_NOMAL);

			int page =  (paramMap.get("page")!=null && !StringUtils.isEmpty(paramMap.get("page").toString())) ? Integer.parseInt(paramMap.get("page").toString()) : 1;
			int rows =  (paramMap.get("rows")!=null && !StringUtils.isEmpty(paramMap.get("rows").toString())) ? Integer.parseInt(paramMap.get("rows").toString()) : 10;

			paramMap.put("start", page);
			paramMap.put("end", rows);

			Object userNameObject = paramMap.get("patientName");
			Object userName = (userNameObject!=null &&!StringUtils.isEmpty(userNameObject)) ? "%"+userNameObject.toString()+"%" : userNameObject ;

			Object hisNo = paramMap.get("hisNo");

			paramMap.put("hisNo",hisNo);
			paramMap.put("userName",userName);
			paramMap.put("phoneNum",paramMap.get("phoneNum"));
			List<String> typeList = ToolUtils.typeCast(paramMap.get("typeList"));
			List<String> examinationPaperNameList = ToolUtils.typeCast(paramMap.get("examinationPaperNameList"));
			if("DST".equals(paramMap.get("examinationPaperName"))){
				list = iEltDstRecoreDAO.selectEltDstRecoreList(paramMap);
			}
			else if(typeList!=null && typeList.size()>0) {
				list = followEvaluationDao.selectEvaluationPatientListOwn(paramMap);
			}else if (examinationPaperNameList!=null && examinationPaperNameList.size()>0){
				list = followEvaluationDao.selectMabcList(paramMap);
			}else{
				list = followEvaluationDao.selectEvaluationPatientList(paramMap);
			}
			Map<String, Object> map =null;
			if(!CollectionUtils.isEmpty(list)){
				if(!"0".equals((String)paramMap.get("showFlag"))) {
					for(int i = 0;i<list.size();i++){
						map = list.get(i);
						list.get(i).put("createTime",DateUtil.getTimeStampSec(map.get("createTime").toString()));
						list.get(i).put("week",ToolUtils.getPregnancyStr((int)map.get("pregnancDay")));
						if(!StringUtils.isEmpty(map.get("birthday"))) {
//							list.get(i).put("age",ToolUtils.getBirthAgeWeek(map.get("birthday").toString()));
							//
							Long birthLong=ToolUtils.getCorrect(map.get("birthday").toString(),(int)map.get("pregnancDay"));//生日时间戳
							Long createTime=ToolUtils.getCorrect(map.get("createTime").toString(),(int)map.get("pregnancDay"));
							int ageMonth=(int)((createTime-birthLong)/(1000*60*60*24)/Constants.MONTH_DAY);
							if(ageMonth>=45 && ageMonth<=51){
								//年龄状态 0：3岁9月-4岁3月龄
								list.get(i).put("ageState","0");
							}else if(ageMonth>=57 && ageMonth<=63){
								//年龄状态 1：4岁9月-5岁3月龄
								list.get(i).put("ageState","1");
							}else if(ageMonth>=69 && ageMonth<=75){
								//年龄状态 2：5岁9月-6岁3月龄
								list.get(i).put("ageState","2");
							}
							list.get(i).put("age",ToolUtils.getAgeMonDayByDate3(DateUtil.getDate_8(new Date(birthLong)),
									map.get("testTime").toString()));
						}
						map = null;
					}
				}else {
					for(int i = 0;i<list.size();i++){
						map = list.get(i);
						list.get(i).put("createTime",DateUtil.getTimeStampSec(map.get("createTime").toString()));
						try{
							if(paramMap.get("authorId").equals(map.get("doctorId"))){
							}else {
								list.get(i).put("flag","1");
							}
						}catch(Exception e) {
						}
						List <PatientContentData> lists =  PatientContentDao.listCntDataByUserIdAndAcceptPrivate(map);
						if(!CollectionUtils.isEmpty(lists)) {
							for(int j = 0;j<lists.size();j++) {
								if(Constants.QUESTION_ID_FOR_WEIGHT.equals(lists.get(j).getQuestionId())) {
									list.get(i).put("weight",lists.get(j).getQuestionAnswer());
								}else if(Constants.QUESTION_ID_FOR_DELIVERY.equals(lists.get(j).getQuestionId())) {
									list.get(i).put("delivery",lists.get(j).getQuestionAnswer());
								}else if(Constants.QUESTION_ID_FOR_OUTPATIENT.equals(lists.get(j).getQuestionId())) {
									list.get(i).put("outpatient",lists.get(j).getQuestionAnswer());
								}else if(Constants.QUESTION_ID_FOR_CARD1.equals(lists.get(j).getQuestionId())) {
									list.get(i).put("socialCard",lists.get(j).getQuestionAnswer());
								}else if(Constants.QUESTION_ID_FOR_CARD2.equals(lists.get(j).getQuestionId())) {
									list.get(i).put("cardNo",lists.get(j).getQuestionAnswer());
								}else if(Constants.QUESTION_ID_FOR_JIUZHENG.equals(lists.get(j).getQuestionId())) {
									list.get(i).put("correctAge",lists.get(j).getQuestionAnswer());
								}
							}
						}
						map = null;
					}
				}

			}
			return list;
	}

	@Override
	public int getEvaluationPatientCount(Map<String, Object> paramMap)
			throws Exception {
		List<String> typeList = ToolUtils.typeCast(paramMap.get("typeList"));
		List<String> examinationPaperNameList = ToolUtils.typeCast(paramMap.get("examinationPaperNameList"));
		if(typeList!=null && typeList.size()>0) {
			return followEvaluationDao.selectEvaluationPatientCountOwn(paramMap);
		}else if (examinationPaperNameList!=null && examinationPaperNameList.size()>0){
			return followEvaluationDao.selectMabcCount(paramMap);
		}else {
			return followEvaluationDao.selectEvaluationPatientCount(paramMap);
		}

	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> getHighPregnantPostion(Map<String, Object> map)
			throws Exception {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION);
			String json = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_HIGH_PREGNANT);

			if(StringUtils.isEmpty(json)){
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("field",Constants.FOLLOW_EVALUATION_PREGNANT_KEY);
				paramMap.put("key",Constants.FOLLOW_EVALUATION_HIGH_PREGNANT);
				FuAssessMentPosition position = followEvaluationDao.selectAssessMentPosition(paramMap);
				if(null != position){
					json = position.getValue();
					jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_HIGH_PREGNANT,json);
				}
			}

			Map<String, Object> postionMap = JSON.parseObject(json,LinkedHashMap.class);
			return postionMap;

		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}

	@Override
	public List<Map<String,Object>> getPregnantSDSPostion(Map<String, Object> map)
			throws Exception {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION);
			String json = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_SDS);

			if(StringUtils.isEmpty(json)){
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("field",Constants.FOLLOW_EVALUATION_PREGNANT_KEY);
				paramMap.put("key",Constants.FOLLOW_EVALUATION_PREGNANT_SDS);
				FuAssessMentPosition position = followEvaluationDao.selectAssessMentPosition(paramMap);
				if(null != position){
					json = position.getValue();
					jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_SDS,json);
				}
			}

			List<Map<String,Object>> postionMap = new ArrayList<Map<String,Object>>();

			JSONArray arr = JSON.parseArray(json);
			for(int i = 0;i<arr.size();i++){
				postionMap.add(arr.getJSONObject(i));
			}
			return postionMap;

		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}

	@Override
	public List<Map<String,Object>> getPregnantSASPostion(Map<String, Object> map)
			throws Exception {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION);
			String json = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_SAS);

			if(StringUtils.isEmpty(json)){
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("field",Constants.FOLLOW_EVALUATION_PREGNANT_KEY);
				paramMap.put("key",Constants.FOLLOW_EVALUATION_PREGNANT_SAS);
				FuAssessMentPosition position = followEvaluationDao.selectAssessMentPosition(paramMap);
				if(null != position){
					json = position.getValue();
					jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_SAS,json);
				}
			}

			List<Map<String,Object>> postionMap = new ArrayList<Map<String,Object>>();
			JSONArray arr = JSON.parseArray(json);
			for(int i = 0;i<arr.size();i++){
				postionMap.add(arr.getJSONObject(i));
			}
			return postionMap;

		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}

	@Override
	public List<Map<String, Object>> getPregnantEPDSPostion(
			Map<String, Object> map) throws Exception {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION);
			String json = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_EPDS);

			if(StringUtils.isEmpty(json)){
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("field",Constants.FOLLOW_EVALUATION_PREGNANT_KEY);
				paramMap.put("key",Constants.FOLLOW_EVALUATION_PREGNANT_EPDS);
				FuAssessMentPosition position = followEvaluationDao.selectAssessMentPosition(paramMap);
				if(null != position){
					json = position.getValue();
					jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_EPDS,json);
				}
			}

			List<Map<String,Object>> postionMap = new ArrayList<Map<String,Object>>();
			JSONArray arr = JSON.parseArray(json);
			for(int i = 0;i<arr.size();i++){
				postionMap.add(arr.getJSONObject(i));
			}
			return postionMap;

		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> getAIMSPostion(Map<String, Object> map)
			throws Exception {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION);
			String json = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_AIMS);

			if(StringUtils.isEmpty(json)){
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("field",Constants.FOLLOW_EVALUATION_PREGNANT_KEY);
				paramMap.put("key",Constants.FOLLOW_EVALUATION_PREGNANT_AIMS);
				FuAssessMentPosition position = followEvaluationDao.selectAssessMentPosition(paramMap);
				if(null != position){
					json = position.getValue();
					jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_AIMS,json);
				}
			}

			Map<String, Object> postionMap = JSON.parseObject(json,LinkedHashMap.class);
			return postionMap;

		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}

	@Override
	public Map<String, Object> modifyGuide(Map<String, Object> map)
			throws Exception {
		String authorId = (String)map.get("authorId");
		String evaluationId = (String)map.get("evaluationId");
		//评估类型
		String type = (String)map.get("examinationPaperName");
		String guide  = (String)map.get("guide");
		String userId  = (String)map.get("userId");
		String remark  = (String)map.get("remark");
		String currentTime = DateUtil.getSysDateA();

		Map<String,Object> paramMap  = new HashMap<String,Object>();
		paramMap.put("evaluationId", evaluationId);
		paramMap.put("userId", userId);
		if(!Constants.FOLLOW_EVALUATION_GROWTH.equals(type)) {
			PtEvaluationResult result = followEvaluationDao.selectEvaluationResult(paramMap);
			if(null == result){
				throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_EVALUATION_NOT_EXIST,"评估记录不存在");
			}
		}else {
			//如果是生长发育,评估id，查询生长发育几记录表
			paramMap.put("id", evaluationId);
			paramMap.put("type", type);
			List<Map<String,Object>> list = familyReportDAO.selectAllGrowthRecords(paramMap);
			if(null == list || list.size()<=0){
				throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_EVALUATION_NOT_EXIST,"生长发育记录不存在");
			}
		}
		Map<String,Object> guideMap = followEvaluationDao.selectEvaluationGuide(paramMap);
		if(null == guideMap){ //新增
			PtEvaluationGuide  ptGuide = new PtEvaluationGuide();
			ptGuide.setCreateAuthor(authorId);
			ptGuide.setCreateTime(currentTime);
			ptGuide.setEvaluationId(evaluationId);
			ptGuide.setGuide(guide);
			ptGuide.setId(SeqUtil.getSeqNo());
			ptGuide.setUpdateAuthor(authorId);
			ptGuide.setUpdateTime(currentTime);
			if(!StringUtils.isEmpty(remark)) {
				//将remark字段当成备注字段
				ptGuide.setRemark(remark);
			}
			if(!StringUtils.isEmpty(type)) {
				ptGuide.setType(type);
			}
			followEvaluationDao.savePtEvaluationGuide(ptGuide);
		}else{//修改
			paramMap.clear();
			paramMap.put("evaluationId",evaluationId);
			paramMap.put("guide",guide);
			if(!StringUtils.isEmpty(remark)) {
				//将remark字段当成备注字段
				paramMap.put("remark",remark);
			}
			paramMap.put("updateAuthor",authorId);
			paramMap.put("updateTime",currentTime);
			followEvaluationDao.updatePtEvaluationGuide(paramMap);
		}
		return null;
	}

	@Override
	public Map<String, Object> getEvaluationGuide(Map<String,Object> paramMap) throws Exception {
		Map<String,Object> guideMap = followEvaluationDao.selectEvaluationGuide(paramMap);
		if(null !=guideMap){
			if(null != guideMap.get("updateTime")){
				guideMap.put("updateTime",DateUtil.getTimeStampSec(guideMap.get("updateTime").toString()));
			}
			if(null != guideMap.get("createTime")){
				guideMap.put("createTime", DateUtil.getTimeStampSec(guideMap.get("createTime").toString()));
			}
		}
		return guideMap;
	}

	@Override
	public List<Map<String, Object>> getEvaluationGuides(Map<String,Object> paramMap) throws Exception {
		List<Map<String, Object>> guideList =  followEvaluationDao.selectEvaluationGuides(paramMap);

		Map<String,Object> guideMap = null;
		if(!CollectionUtils.isEmpty(guideList)){
			for(int i =0;i<guideList.size();i++){
				guideMap = guideList.get(i);
				if(null !=guideMap){
					if(null != guideMap.get("updateTime")){
						guideList.get(i).put("updateTime",DateUtil.getTimeStampSec(guideMap.get("updateTime").toString()));
					}
					if(null != guideMap.get("createTime")){
						guideList.get(i).put("createTime", DateUtil.getTimeStampSec(guideMap.get("createTime").toString()));
					}
				}
			}
		}
		return guideList;
	}

	@Override
	public Map<String, Object> getAimsCurvedata(Map<String, Object> paramMap)
			throws Exception {
		//返回曲线数据
		Map<String, Object> curaDataMap  =  new HashMap<String, Object>();
		String evaluationId =  (String)paramMap.get("evaluationId");
		String examinationPaperName =  (String)paramMap.get("examinationPaperName");
		String userId = (String)paramMap.get("userId");
		String tenantId = (String)paramMap.get("tenantId");

		Map<String,Object> userPara = new HashMap<String,Object>();
		userPara.put("userId",userId);
		userPara.put("tenantId",tenantId);
		Patient patient = patientdao.selectById(userPara);
		if(null == patient){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,"评估记录患者信息不存在");
		}

		String birthday=patient.getBirthday();
		if(null == birthday){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_BIRTHDAY_NOT_EXIST,"用户没有出生日期");
		}

		Long birthLong=ToolUtils.getCorrect(birthday, patient.getPregnancyDay());//生日时间戳

		List<String> typeList = new ArrayList<String>();
		typeList.add(examinationPaperName);
		paramMap.put("typeList",typeList);
		List<Map<String,Object>> detailsListQry = followEvaluationDao.selectEvaluationResults(paramMap);

		Object testTimeHis=null;
		Object testTime=null;  //本次监测时间  计算出统计单位   周 、月 、年
		//计算当前节点X轴
		long endTime =0;
		long endTimeHis = 0;

		Set<Object> set = new HashSet<Object>();
		List<Map<String,Object>> detailsList = new ArrayList<Map<String,Object>>();

		//同一天只取最新的一条  并且测试时间为空的数据 过滤掉
		if(!CollectionUtils.isEmpty(detailsListQry)){
			for(int j =0;j<detailsListQry.size();j++){
				Object testTimeTemp = detailsListQry.get(j).get("testTime");
				if(null == testTimeTemp){//测试时间为空 过滤
					continue;
				}
				if(detailsListQry.get(j).get("answerId").equals(evaluationId)){
					//当前记录
					testTime=testTimeTemp;
					detailsList.add(detailsListQry.get(j));
					set.add(testTimeTemp.toString());
				}
				if(set.contains(testTimeTemp.toString())){
					continue;
				}else{
					set.add(testTimeTemp.toString());
					detailsList.add(detailsListQry.get(j));
				}
			}
		}

		curaDataMap.put("timeUnit","月");
		curaDataMap.put("xMin",0);
		curaDataMap.put("xMax", 19);
		curaDataMap.put("yMin",0);
		curaDataMap.put("yMax",60);

		float xdate = 0,timeUnitLong = 30.4F;
		Map<String,Object> map = null;
		Map<String,Object> detailsMap = null;

		List<Map<String,Object>> records = new ArrayList<Map<String,Object>>();

		if(!CollectionUtils.isEmpty(detailsList)){
			for(int j =0;j<detailsList.size();j++){
				detailsMap = detailsList.get(j);
				map = new HashMap<String,Object>();
				int flag = 0;//是否当前记录
				if(detailsMap.get("answerId").equals(evaluationId)){
					flag = 1;//当前记录
					endTime = (DateUtil.getDate_8(testTime.toString()).getTime()-birthLong)/(1000*60*60*24);
					xdate = endTime / timeUnitLong;
				}else{
					//
					if(detailsMap.get("testTime").equals(testTime)){//删除日期和当前记录相等的
						continue;
					}
					testTimeHis = detailsMap.get("testTime");//计算每次记录的 X轴
					endTimeHis = (DateUtil.getDate_8(testTimeHis.toString()).getTime()-birthLong)/(1000*60*60*24);
					xdate = endTimeHis / timeUnitLong;//小于0 不用处理
				}
			    map.put("xDate",xdate);
			    map.put("flag",flag);

			    try{
				    if(null != detailsMap.get("result")){
				    	String total = (String)detailsMap.get("result");
				    	JSONObject jsonObj = JSON.parseObject(total);
				    	if(null != jsonObj.getJSONObject("total")){
				    		int totalScore = jsonObj.getJSONObject("total").getIntValue("totalScore");
					    	String percent = jsonObj.getJSONObject("total").getString("percent");
					    	map.put("yDate",totalScore);
					    	map.put("percent",percent);
					    	records.add(map);
				    	}
				    }
			    }catch(Exception e){
					logger.error("查询评估记录历史数据异常",e);
				}
			}
		}

		curaDataMap.put("records",records);

		String redisKey = Constants.AIMS_DEVELOPPROJECT_SCORE;
		//先从缓存查询  没有再查询数据库
		Jedis jedis = null;
		Map<String,Object> standardMap = null;
        try {
            jedis = jedisPool.getResource();
            jedis.select(Constants.REDIS_DB_INDEX_EVALUATION);
            String str = jedis.get(Constants.AIMS_STANDARD_KEY+redisKey);

            if(!StringUtils.isEmpty(str)){
            	standardMap = JSONObject.parseObject(str);
        	}

            if(null == standardMap){ //缓存数据为空
            	standardMap = new HashMap<String,Object>();

            	List<BsEvaluationStandard> standardList = new ArrayList<BsEvaluationStandard>();
        		Map<String,Object>  standardParam = new HashMap<String,Object>();

        		standardParam.put("projectId",Constants.AIMS_DEVELOPPROJECT_SCORE);
        		standardParam.put("standardId",Constants.AIMS_STANDARD_ID);
        		standardParam.put("standardType",Constants.AIMS_STANDARD_TYPE_PERCENT);
        		standardList = followEvaluationDao.selectEvaluationStandardsAll(standardParam);
        		if(CollectionUtils.isEmpty(standardList)){
        			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_GROWTHS_STANDARD_WHO_NOT_EXIST,"ALberta婴儿运动量表百分位数据不存在");
        		}

        		BsEvaluationStandard temp = null;
        		ArrayList<Object[]> p5 = new ArrayList<Object[]>();
        		ArrayList<Object[]> p10 = new ArrayList<Object[]>();
        		ArrayList<Object[]> p25 = new ArrayList<Object[]>();
        		ArrayList<Object[]> p50 = new ArrayList<Object[]>();
        		ArrayList<Object[]> p75 = new ArrayList<Object[]>();
        		ArrayList<Object[]> p90 = new ArrayList<Object[]>();


        		for(int i = 0; i<standardList.size();i++){
        			temp = standardList.get(i);
        			//
        			float age = temp.getAge();
        			p5.add(new Object[]{age,temp.getP5()});
        			p10.add(new Object[]{age,temp.getP10()});
    				p25.add(new Object[]{age,temp.getP25()});
    				p50.add(new Object[]{age,temp.getP50()});
    				p75.add(new Object[]{age,temp.getP75()});
    				p90.add(new Object[]{age,temp.getP90()});
        		}
        		standardMap.put("P5",p5);
        		standardMap.put("P10",p10);
        		standardMap.put("P25",p25);
        		standardMap.put("P50",p50);
        		standardMap.put("P75",p75);
        		standardMap.put("P90",p90);

        		jedis.set(Constants.AIMS_STANDARD_KEY+redisKey,JSONObject.toJSONString(standardMap));
            }

        } catch (JedisConnectionException jex) {
            logger.error("redis连接异常..." + jex.getMessage());
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR, "Redis缓存连接失败!"));
        } finally {
            if (null != jedis) {
                try {
                    jedis.close();
                    logger.warn("close redis connection...");
                } catch (Exception ex) {
                    ex.printStackTrace();
                    throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
                }
            }
        }
        curaDataMap.putAll(standardMap);
		return curaDataMap;
	}

	@Override
	public Map<String, Object> selectPtEvaluationResultDetail(
			Map<String, Object> paramMap) throws Exception {
		String examinationPaperName = (String) paramMap.get("examinationPaperName");
		Map<String, Object> map = followEvaluationDao.selectEvaluationResultDetail(paramMap);
		//查询医生信息
		if (null != map) {
			map.put("createTime",DateUtil.getTimeStampSec(map.get("createTime").toString()));
			if(null !=map.get("testName") ){
				map.put("testName",map.get("testName").toString());
			}
			if (null != map.get("pregnancyday")) {
				long pregnancyday = Long.parseLong(map.get("pregnancyday")
						.toString());
				if (pregnancyday < 280) {
					map.put("userType", "01");// 早产儿
				} else {
					map.put("userType", "02");
				}
			}

			Map<String, Object> param = new HashMap<String, Object>();
			param.put("id",map.get("doctorId"));
			Doctor doctor = doctorDao.selectById(param);
			if(null != doctor){
				map.put("doctorName",doctor.getDoctorName());
				map.put("deptName",doctor.getDeptName());
				map.put("hospName",doctor.getHospName());
				map.put("deptPhone",doctor.getDeptPhone());
			}

		 if (Constants.FOLLOW_EVALUATION_PREGNANT_BSID2.equals(examinationPaperName)||Constants.FOLLOW_EVALUATION_PREGNANT_GMS.equals(examinationPaperName)) {
	            List<PtArchiveData> lists = PtArchiveDataDAO.listArchiveDataByUserIdAndAcceptPrivate(paramMap);
	            if (!CollectionUtils.isEmpty(lists)) {
	                for (int j = 0; j < lists.size(); j++) {
	                    if (Constants.QUESTION_ID_FOR_NFYYBIRTHWEIGHT.equals(lists.get(j).getQuestionId())) {
	                    	map.put("nfyybirthweight", (String)lists.get(j).getQuestionAnswer());// 出生体重
	                    } else if (Constants.QUESTION_ID_FOR_PREGNANCT_NO.equals(lists.get(j).getQuestionId())) {
	                    	map.put("newId", (String)lists.get(j).getQuestionAnswer());//编号
	                    } else if (Constants.QUESTION_ID_FOR_NFYYFEEDWAY.equals(lists.get(j).getQuestionId())) {
	                    	map.put("nfyyfeedway", (String)lists.get(j).getQuestionAnswer());// 喂养方式
	                    } else if (Constants.QUESTION_ID_FOR_NFYYPARITY.equals(lists.get(j).getQuestionId())) {
	                    	map.put("nfyyParity", (String)lists.get(j).getQuestionAnswer());// 胎次
	                    } else if (Constants.QUESTION_ID_FOR_NFYYPRODUCTIONTIMES.equals(lists.get(j).getQuestionId())) {
	                    	map.put("nfyyProductiontimes", (String)lists.get(j).getQuestionAnswer());// 产次
	                    }
	                }
	            }
	        }
		}

		return map;
	}

	@Override
	public List<JSONObject> getPregnantCommonPostion(
			Map<String, Object> map) throws Exception {
		Jedis jedis = null;
		String key = (String)map.get("evaluationType");
		Patient pt = (Patient)map.get("Patient");
		Object month = map.get("ageMonth");
		long ageMonth = 0;
		if(!StringUtils.isEmpty(month)){
			ageMonth = (long)month;
		}else{
			Long birthLong=ToolUtils.getCorrect(pt.getBirthday(),pt.getPregnancyDay());//生日时间戳
//			int ageMonth = ToolUtils.getAgeMonthByBirthday(DateUtil.getDate_8(new Date()),DateUtil.getDate_8(new Date(birthLong)));
			String testTime = (String)map.get("testTime");
			if(StringUtils.isEmpty(testTime)){
				ageMonth=(long) ((new Date().getTime()-birthLong)/(1000*60*60*24)/30);
			}else{
				ageMonth=(long)((DateUtil.getDate_8(testTime).getTime()-birthLong)/(1000*60*60*24)/30);
			}
		}

		if(Constants.FOLLOW_EVALUATION_PREGNANT_ASQ.equals(key)){
			if(ageMonth >= 1 && ageMonth<3){
				key =  key+"_"+2;
			}else if (ageMonth >=3 && ageMonth<5){
				key =  key+"_"+4;
			}else if (ageMonth >=5 && ageMonth<7){
				key =  key+"_"+6;
			}else if (ageMonth >=7 && ageMonth<9){
				key =  key+"_"+8;
			}else if (ageMonth >=9 && ageMonth<11){
				key =  key+"_"+10;
			}else if (ageMonth >=11 && ageMonth<13){
				key =  key+"_"+12;
			}else if (ageMonth >=13 && ageMonth<15){
				key =  key+"_"+14;
			}else if (ageMonth >=15 && ageMonth<17){
				key =  key+"_"+16;
			}else if (ageMonth >=17 && ageMonth<19){
				key =  key+"_"+18;
			}
		}
		List<JSONObject> postionMap = new ArrayList<JSONObject>();
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION);
			String json = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,key);

			if(StringUtils.isEmpty(json)){
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("field",Constants.FOLLOW_EVALUATION_PREGNANT_KEY);
				paramMap.put("key",key);
				FuAssessMentPosition position = followEvaluationDao.selectAssessMentPosition(paramMap);
				if(null != position){
					json = position.getValue();
					jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,key,json);
				}
			}

			JSONArray arr = JSON.parseArray(json);
			if(arr == null || arr.size() ==0){ //没有问题
				return postionMap;
			}

			for(int i = 0;i<arr.size();i++){
				if(Constants.FOLLOW_EVALUATION_PREGNANT_AHEMD.equals(key) && ageMonth <=11){
					//3-1 养育 1-26题
					JSONObject object = arr.getJSONObject(i);
					int id = object.getIntValue("id");
					if(id <= 26){
						postionMap.add(arr.getJSONObject(i));
					}
				}else{
					postionMap.add(arr.getJSONObject(i));
				}
			}
			return postionMap;

		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}

	@Override
	public Map<String, Object> getAnswerDetail(Map<String, Object> map)
			throws Exception {
		Jedis jedis = null;
		Map<String, Object> resultMap = this.selectPtEvaluationResultDetail(map);
		if(null == resultMap){
			return null;
		}

		try {
			String evaluationType =(String)resultMap.get("type");
			map.put("evaluationType", evaluationType);
			List<JSONObject> postionList = this.getPregnantCommonPostion(map);//获取问卷
			String result = (String)resultMap.get("answerResult");
			//传入答题 结果
			JSONObject jsonEsb = JSON.parseObject(result);
			for(int i = 0 ;i<postionList.size();i++){
				String id = postionList.get(i).getString("id");
				String type = postionList.get(i).getString("type");
				String answerId = jsonEsb.getString(id);
				JSONArray answers =  null;
				if(Constants.EVALUATION_QUESTION_ANSWER_OPTION_RADIO.equals(type) || StringUtils.isEmpty(type)){
					answers = postionList.get(i).getJSONArray("answer");
					if(null != answers && !StringUtils.isEmpty(answerId)){
						for(int j = 0 ;j<answers.size();j++){
							JSONObject obj = answers.getJSONObject(j);
							String idStr = obj.getString("id");
							//SDQ答案获取 APP特殊处理
							if(answerId.equals(idStr)){
								obj.put("checked",true);
							}
						}
					}
				}else if(Constants.EVALUATION_QUESTION_ANSWER_OPTION_TEXT.equals(type)){
					postionList.get(i).put("note",answerId);
				}
			}
			resultMap.put("answerResult",postionList);
			return resultMap;
		}catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		}finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> getPregnantPeabodyPostion(Map<String, Object> paramsMap) throws Exception{
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION);
			String json1 = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_PEABODY_1);
			String json2 = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_PEABODY_2);
			String json3 = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_PEABODY_3);
			String json4 = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_PEABODY_4);
			String json5 = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_PEABODY_5);
			String json6 = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_PEABODY_6);
			if(StringUtils.isEmpty(json1)||StringUtils.isEmpty(json2)||StringUtils.isEmpty(json3)||StringUtils.isEmpty(json4)||StringUtils.isEmpty(json5)||StringUtils.isEmpty(json6)){
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("field",Constants.FOLLOW_EVALUATION_PREGNANT_KEY);
				paramMap.put("type",Constants.FOLLOW_EVALUATION_PREGNANT_PEABODY);
				List<FuAssessMentPosition> positions = followEvaluationDao.selectAssessMentPositionBytype(paramMap);
				if(null != positions){
					for(int i =0;i<positions.size();i++) {
						FuAssessMentPosition position =  positions.get(i);
						if(Constants.FOLLOW_EVALUATION_PREGNANT_PEABODY_1.equals(position.getKey())) {
							json1 = position.getValue();
							jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_PEABODY_1,json1);
						}else if(Constants.FOLLOW_EVALUATION_PREGNANT_PEABODY_2.equals(position.getKey())) {
							json2 = position.getValue();
							jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_PEABODY_2,json2);
						}else if(Constants.FOLLOW_EVALUATION_PREGNANT_PEABODY_3.equals(position.getKey())) {
							json3 = position.getValue();
							jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_PEABODY_3,json3);
						}else if(Constants.FOLLOW_EVALUATION_PREGNANT_PEABODY_4.equals(position.getKey())) {
							json4 = position.getValue();
							jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_PEABODY_4,json4);
						}else if(Constants.FOLLOW_EVALUATION_PREGNANT_PEABODY_5.equals(position.getKey())) {
							json5 = position.getValue();
							jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_PEABODY_5,json5);
						}else if(Constants.FOLLOW_EVALUATION_PREGNANT_PEABODY_6.equals(position.getKey())) {
							json6 = position.getValue();
							jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_PEABODY_6,json6);
						}
					}
				}
			}
			Map<String, Object> mapOut = new LinkedHashMap<String, Object>();
			mapOut.put("反射", net.sf.json.JSONArray.fromObject(json1));
			mapOut.put("姿势", net.sf.json.JSONArray.fromObject(json2));
			mapOut.put("移动", net.sf.json.JSONArray.fromObject(json3));
			mapOut.put("实物操作", net.sf.json.JSONArray.fromObject(json4));
			mapOut.put("抓握", net.sf.json.JSONArray.fromObject(json5));
			mapOut.put("视觉-运动", net.sf.json.JSONArray.fromObject(json6));
			Map<String, Object> postionMap = net.sf.json.JSONObject.fromObject(mapOut);
			return postionMap;

		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}

	// peabody业务逻辑层
	@Override
	public Map<String, Object> getPeabodydata(Map<String, Object> paramMap) throws Exception {
		// 返回曲线数据
		Map<String, Object> curaDataMap = new HashMap<String, Object>();
		String examinationPaperName = (String) paramMap.get("examinationPaperName");
		String userId = (String) paramMap.get("userId");
		String tenantId = (String) paramMap.get("tenantId");

		Map<String, Object> userPara = new HashMap<String, Object>();
		userPara.put("userId", userId);
		userPara.put("tenantId", tenantId);
		Patient patient = patientdao.selectById(userPara);
		if (null == patient) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST, "评估记录患者信息不存在");
		}

		String birthday = patient.getBirthday();
		if (null == birthday) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_BIRTHDAY_NOT_EXIST, "用户没有出生日期");
		}

		paramMap.put("type", examinationPaperName);
		PtEvaluationResult result = followEvaluationDao.selectEvaluationResult(paramMap);
		if (null == result) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_EVALUATION_NOT_EXIST, "评估记录不存在");
		}

		return curaDataMap;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> getPregnantBSIDPostion(
			Map<String, Object> paramsMap) throws Exception {
		Jedis jedis = null;
		String key = Constants.FOLLOW_EVALUATION_PREGNANT_BSID;
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION);
			String json = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,key);

			if(StringUtils.isEmpty(json)){
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("field",Constants.FOLLOW_EVALUATION_PREGNANT_KEY);
				paramMap.put("key",key);
				FuAssessMentPosition position = followEvaluationDao.selectAssessMentPosition(paramMap);
				if(null != position){
					json = position.getValue();
					jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,key,json);
				}
			}

			Map<String, Object> postionMap = JSON.parseObject(json,LinkedHashMap.class,Feature.OrderedField);
			return postionMap;

		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> getPregnantBSID2Postion(Map<String, Object> paramsMap) throws Exception {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION);
			String json1 = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_BSID2_PR);
			String json2 = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_BSID2_MR);
			String json3 = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_BSID2_ACTIVITY);
			if(StringUtils.isEmpty(json1)||StringUtils.isEmpty(json2)||StringUtils.isEmpty(json3)){
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("field",Constants.FOLLOW_EVALUATION_PREGNANT_KEY);
				paramMap.put("type",Constants.FOLLOW_EVALUATION_PREGNANT_BSID2);
				List<FuAssessMentPosition> positions = followEvaluationDao.selectAssessMentPositionBytype(paramMap);
				if(null != positions){
					for(int i =0;i<positions.size();i++) {
						FuAssessMentPosition position =  positions.get(i);
						if(Constants.FOLLOW_EVALUATION_PREGNANT_BSID2_PR.equals(position.getKey())) {
							json1 = position.getValue();
							jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_BSID2_PR,json1);
						}else if(Constants.FOLLOW_EVALUATION_PREGNANT_BSID2_MR.equals(position.getKey())) {
							json2 = position.getValue();
							jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_BSID2_MR,json2);
						}else if(Constants.FOLLOW_EVALUATION_PREGNANT_BSID2_ACTIVITY.equals(position.getKey())) {
							json3 = position.getValue();
							jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_BSID2_ACTIVITY,json3);
						}
					}
				}
			}
			Map<String, Object> mapOut = new LinkedHashMap<String, Object>();
			mapOut.put("智力", net.sf.json.JSONArray.fromObject(json2));
			mapOut.put("运动", net.sf.json.JSONArray.fromObject(json1));
			mapOut.put("行为", net.sf.json.JSONObject.fromObject(json3));
			Map<String, Object> postionMap = net.sf.json.JSONObject.fromObject(mapOut);
			return postionMap;

		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}

	//获取指导意见
	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> getEvaluationGuideByAge(Map<String, Object> map) throws Exception {
		int age = Integer.parseInt((String)map.get("age"));
		Jedis jedis = null;
		String keys = Constants.FOLLOW_EVALUATION_PREGNANT_BSID_GUIDE;
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION);
			String json = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,keys);

			if(StringUtils.isEmpty(json)){
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("field",Constants.FOLLOW_EVALUATION_PREGNANT_KEY);
				paramMap.put("key",keys);
				FuAssessMentPosition position = followEvaluationDao.selectAssessMentPosition(paramMap);
				if(null != position){
					json = position.getValue();
					jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,keys,json);
				}
			}
			int mouth = age/30;//月龄
			net.sf.json.JSONObject finalJson = net.sf.json.JSONObject.fromObject(json);
			if(mouth>2) {
				String [] arg = null;
				Iterator<?> iterator = finalJson.keys();
	            while(iterator.hasNext()){
                    String key = (String) iterator.next();
                    if(key.indexOf("-")==-1) {
                    	if((mouth+"").equals(key)) {
                    		json = finalJson.get(key).toString();
                    	}
                    }else {
                    	arg = key.split("-");
                    	if(mouth>=Integer.parseInt(arg[0]) && Integer.parseInt(arg[1])>=mouth) {
                    		json = finalJson.get(key).toString();
                    	}
                    }
	            }
			}else {
				json = finalJson.get("29-60").toString();
			}
			Map<String, Object> postionMap = JSON.parseObject(json,LinkedHashMap.class,Feature.OrderedField);
			return postionMap;

		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> getWorkOrderReport(Map<String,Object> paramMap) throws Exception {
		Map<String, Object> allMap  = new HashMap<String, Object>();

//		Map<String, Object> healthguide  = new HashMap<String, Object>();
//		Map<String, Object> growthguide  = new HashMap<String, Object>();
//		Map<String, Object> ahemdguide  = new HashMap<String, Object>();
//		Map<String, Object> asqguide  = new HashMap<String, Object>();
		Map<String, Object> growthMap  = new HashMap<String, Object>();
		Map<String, Object> asqMap  = new HashMap<String, Object>();
		Map<String, Object> ahemdMap  = new HashMap<String, Object>();

		//查询订单信息
		Map<String, Object> orderMap = evaluationWorkOrderService.getEvaluationMonthRecordDetail(paramMap);

		String birthdayStr="";
		int pregnancyDay=0 ;
		if(null == orderMap){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"评估记录不存在");
		}else{
			//根据状态 如果未评估完成 则提示还未评估 TODO

			//根据医生id 查询科室名称
			String doctorId = (String)orderMap.get("doctorId");
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("id",doctorId);
			Doctor doctor = doctorManagerService.getDoctorById(map);
			String deptName ="";
			String hospName ="";
			if(null != doctor){
				deptName = doctor.getDeptName();
				hospName = doctor.getHospName();
				orderMap.put("doctorName",doctor.getDoctorName());
			}
			orderMap.put("doctorHospName", hospName);
			orderMap.put("doctorDeptName", deptName);

		    birthdayStr = orderMap.get("birthday").toString();
			Object pregnancyDayStr = orderMap.get("pregnancyDay");
			Long birthLong = 0L;
			if(StringUtils.isEmpty(pregnancyDayStr)){
				birthLong = ToolUtils.getCorrect(birthdayStr,null);//生日时间戳
			}else{
				pregnancyDay = Integer.parseInt(pregnancyDayStr.toString());
				birthLong = ToolUtils.getCorrect(birthdayStr,pregnancyDay);//生日时间戳
			}
			String createTime = (String)orderMap.get("createTime");
			String age = ToolUtils.getCommAgeByBirthday(createTime,DateUtil.getDate_8(new Date(birthLong)));
			orderMap.put("age",age);
		}

		//id + 租户id
		//查询生长发育记录
		String userId = (String)orderMap.get("userId");
		String tenantId = (String)orderMap.get("tenantId");
		String growthRecordId = "";
		Map<String,Object> heightMap = new HashMap<String,Object>();
		Map<String,Object> weightMap = new HashMap<String,Object>();
		Map<String,Object> headtMap = new HashMap<String,Object>();
		List<Map<String,Object>> growthlist = evaluationWorkOrderDAO.selectGrowthDetailByOrderId(paramMap);
		if(!CollectionUtils.isEmpty(growthlist)){
			growthRecordId  = (String)growthlist.get(0).get("growthRecordId");
			Map<String,Object> map = growthlist.get(0);
			JSONObject  obj = JSON.parseObject(map.get("result").toString());
			JSONArray weightResult = obj.getJSONArray("weightResult");
			JSONArray heightResult = obj.getJSONArray("heightResult");
			JSONArray headtResult = obj.getJSONArray("headtResult");

			if(null !=weightResult && weightResult.size()> 0){
				weightMap.put("percentileRange", weightResult.getJSONObject(0).get("percentileRange"));
			}
			weightMap.put("weight",map.get("weight"));
			if(null !=heightResult && heightResult.size()> 0){
				heightMap.put("percentileRange", heightResult.getJSONObject(0).get("percentileRange"));
			}
			heightMap.put("height",map.get("height"));
			if(null !=headtResult && headtResult.size()> 0){
				headtMap.put("percentileRange", headtResult.getJSONObject(0).get("percentileRange"));
			}
			headtMap.put("headCircumference",map.get("headCircumference"));
			growthMap.put("height",heightMap);
			growthMap.put("weight",weightMap);
			growthMap.put("head",headtMap);
			allMap.put("growthInfo", growthMap);
		}

		//查询 智能发育 养育环境记录
		List<Map<String,Object>> list = evaluationWorkOrderDAO.selectEvaluaTionDetailByOrderId(paramMap);
		if(!CollectionUtils.isEmpty(list)){
			for(int i = 0;i<list.size();i++){
				Map<String,Object> map = list.get(i);
				String type = (String)map.get("type");
				if(Constants.FOLLOW_EVALUATION_PREGNANT_AHEMD.equals(type)){
					if(null!=map && !StringUtils.isEmpty(map.get("result"))){
						JSONObject obj = JSON.parseObject(map.get("result").toString());
//						ahemdMap.put("score", obj.get("score"));
			             if(null != obj){
			            	 ahemdMap.putAll(obj);
			             }
					}

		            Long birthLong=ToolUtils.getCorrect(birthdayStr,pregnancyDay);//生日时间戳
		      		long ageDay = (DateUtil.getDate_8(map.get("testTime").toString()).getTime()-birthLong)/(1000*60*60*24);
		            long ageMonth = (long) (ageDay/30.4);
		            ahemdMap.put("ageMonth",ageMonth+"月龄");
		            ahemdMap.put("testTime",map.get("testTime").toString());
		            ahemdMap.put("answerId",map.get("answerId").toString());

					allMap.put("ahemdInfo",ahemdMap);
				}else if(Constants.FOLLOW_EVALUATION_PREGNANT_ASQ.equals(type)){
					if(null!=map && !StringUtils.isEmpty(map.get("result"))){
						JSONObject obj = JSON.parseObject(map.get("result").toString());
//						asqMap.put("score", obj.get("score"));
						  if(null != obj){
							  asqMap.putAll(obj);
				             }
					}
					Long birthLong=ToolUtils.getCorrect(birthdayStr,pregnancyDay);//生日时间戳
		      		long ageDay = (DateUtil.getDate_8(map.get("testTime").toString()).getTime()-birthLong)/(1000*60*60*24);
		            long ageMonth = (long) (ageDay/30.4);
		            asqMap.put("ageMonth",ageMonth+"月龄");
		            asqMap.put("testTime",map.get("testTime").toString());
		            asqMap.put("answerId",map.get("answerId").toString());

					allMap.put("asqInfo",asqMap);
				}
			}
		}

		//查询曲线数据
		paramMap.put("growthRecordId",growthRecordId);
		paramMap.put("userId",userId);
		paramMap.put("tenantId",tenantId);
		Map<String, Object> retOut = familyReportService.getGrowthCurvedata(paramMap);

		if(!CollectionUtils.isEmpty(retOut)){
			List<Map<String,Object>> curvadataList =  null;
			String curveType = (String)retOut.get("curveType");
			growthMap.put("curveType", curveType); //曲线类型
			if(null != retOut.get("curvadataList")){
				curvadataList =(List<Map<String,Object>>)retOut.get("curvadataList");
				for(int i = 0;i<curvadataList.size();i++){
					Map<String,Object> map = curvadataList.get(i);
					String type = (String)map.get("type");
					if(Constants.DEVELOPPROJECT_HEAD.equals(type)){
						headtMap.put("curvedata", map.get("curvedata"));
					}else if(Constants.DEVELOPPROJECT_LENGTH.equals(type)){
						heightMap.put("curvedata", map.get("curvedata"));
					}if(Constants.DEVELOPPROJECT_WEIGHT.equals(type)){
						weightMap.put("curvedata", map.get("curvedata"));
					}
				}
			}
		}

		//查询指导意见
		List<Map<String,Object>> guideList = evaluationWorkOrderDAO.selectEvaluaTionManualGuide(paramMap);
		if(!CollectionUtils.isEmpty(guideList)){
			for(int i = 0;i<guideList.size();i++){
				Map<String,Object> map = guideList.get(i);
				if("01".equals(map.get("type"))){
//					guide.put("growthguide", map.get("guide"));
					if(null!=map && !StringUtils.isEmpty(map.get("guide"))){
						JSONObject obj = JSON.parseObject(map.get("guide").toString());
						headtMap.put("guide", obj.get("head"));
						weightMap.put("guide", obj.get("weight"));
						heightMap.put("guide", obj.get("height"));
					}
				}else if("02".equals(map.get("type"))){
//					guide.put("asqguide", map.get("guide"));
					if(null!=map && !StringUtils.isEmpty(map.get("guide"))){
						JSONObject obj = JSON.parseObject(map.get("guide").toString());
						asqMap.put("guide", obj.get("suggest"));
					}
				}else if("03".equals(map.get("type"))){
//					guide.put("ahemdguide", map.get("guide"));
					if(null!=map && !StringUtils.isEmpty(map.get("guide"))){
						JSONObject obj = JSON.parseObject(map.get("guide").toString());
						ahemdMap.put("guide", obj.get("suggest"));
					}
				}else if("04".equals(map.get("type"))){
					if(null!=map && !StringUtils.isEmpty(map.get("guide"))){
						JSONObject obj = JSON.parseObject(map.get("guide").toString());
						allMap.put("healthguide", obj);
					}
				}else if("05".equals(map.get("type"))){
					if(null!=map && !StringUtils.isEmpty(map.get("guide"))){
						JSONObject obj = JSON.parseObject(map.get("guide").toString());
						allMap.put("allguide", obj);
					}
				}
			}
		}

//		allMap.put("guides", guide);
		allMap.put("userInfo",orderMap);
		return allMap;
	}

	//气质评估指导意见
	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> getTEMPGuide(Map<String, Object> param, Patient pt) throws Exception {
		Jedis jedis = null;
		String keys = Constants.FOLLOW_EVALUATION_TEMP;
		//纠正胎龄不足280天，月龄 = 当前日期 - 预产期， 预产期 = 出生日期 +（280 - 纠正胎龄）;
		Date birthday = DateUtil.getDate_8(pt.getBirthday());
		int days = DateUtil.daysBetween(birthday, new Date());
		int month = days % 30 > 15 ? days / 30 + 1 : days / 30;
		if(pt.getPregnancyDay()<260 && month<25 && pt.getPregnancyDay()>0) {
			int day = 280 - pt.getPregnancyDay();
			birthday = DateUtil.addDay(birthday, day);
		}
		days = DateUtil.daysBetween(birthday, new Date());
		month = days % 30 > 15 ? days / 30 + 1 : days / 30;
		if(0<=month && month<=3) {
			try {
				jedis = jedisPool.getResource();
				jedis.select(Constants.REDIS_DB_INDEX_EVALUATION);
				String json = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,keys);

				if(StringUtils.isEmpty(json)){
					Map<String, Object> paramMap = new HashMap<String, Object>();
					paramMap.put("field",Constants.FOLLOW_EVALUATION_PREGNANT_KEY);
					paramMap.put("key",keys);
					FuAssessMentPosition position = followEvaluationDao.selectAssessMentPosition(paramMap);
					if(null != position){
						json = position.getValue();
						jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,keys,json);
					}
				}
				net.sf.json.JSONObject finalJson = net.sf.json.JSONObject.fromObject(json);
				try {
					json = finalJson.get(param.get("type")).toString();
				} catch (Exception e) {
					json = (String)finalJson.get(param.get("type"));
				}
				if(!StringUtils.isEmpty(json)) {
					Map<String, Object> postionMap = JSON.parseObject(json,LinkedHashMap.class,Feature.OrderedField);
					return postionMap;
				}else {
					return null;
				}

			} catch (JedisConnectionException jex) {
				logger.error("redis连接异常..." + jex.getMessage());
				throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
			} finally {
				if (null != jedis) {
					try {
						jedis.close();
						logger.warn("close redis connection...");
					} catch (Exception ex) {
						ex.printStackTrace();
						throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
					}
				}
			}
		}else {
			return null;
		}
	}

	@Override
	public Map<String,Object> getPregnantSDS2Postion(Map<String, Object> map)
			throws Exception {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION);
			String json = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_SDS2);

			if(StringUtils.isEmpty(json)){
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("field",Constants.FOLLOW_EVALUATION_PREGNANT_KEY);
				paramMap.put("key",Constants.FOLLOW_EVALUATION_PREGNANT_SDS2);
				FuAssessMentPosition position = followEvaluationDao.selectAssessMentPosition(paramMap);
				if(null != position){
					json = position.getValue();
					jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_SDS2,json);
				}
			}

			Map<String,Object> postionMap = new HashMap<String,Object>();

			postionMap = ToolUtils.typeCast(JSON.parse(json));
			return postionMap;

		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}

	@Override
	public Map<String,Object> getPregnantSAS2Postion(Map<String, Object> map)
			throws Exception {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION);
			String json = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_SAS2);

			if(StringUtils.isEmpty(json)){
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("field",Constants.FOLLOW_EVALUATION_PREGNANT_KEY);
				paramMap.put("key",Constants.FOLLOW_EVALUATION_PREGNANT_SAS2);
				FuAssessMentPosition position = followEvaluationDao.selectAssessMentPosition(paramMap);
				if(null != position){
					json = position.getValue();
					jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,Constants.FOLLOW_EVALUATION_PREGNANT_SAS2,json);
				}
			}

			Map<String,Object> postionMap = new HashMap<String,Object>();
			postionMap = ToolUtils.typeCast(JSON.parse(json));
			return postionMap;

		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}

	//获取Gms评估信息
	@Override
	public Map<String, Object> selectGmsResultDetail(Map<String, Object> map) throws Exception {
		logger.info("map = "+map.toString());
		List<Map<String, Object>>  paramMap1 = followEvaluationDao.selectEvaluationResultDate(map);
		Map<String, Object> paramMap = new LinkedHashMap<String, Object>();
		//查询医生信息
		if (null != paramMap1 && paramMap1.size()>0) {
			for(int i=0;i<paramMap1.size();i++) {
				paramMap1.get(i).put("createTime",DateUtil.getTimeStampSec(paramMap1.get(i).get("createTime").toString()));
				if(null !=paramMap1.get(i).get("testName") ){
					paramMap1.get(i).put("testName",paramMap1.get(i).get("testName").toString());
				}
				if (null != paramMap1.get(i).get("pregnancyday")) {
					long pregnancyday = Long.parseLong(paramMap1.get(i).get("pregnancyday")
							.toString());
					if (pregnancyday < 280) {
						paramMap1.get(i).put("userType", "01");// 早产儿
					} else {
						paramMap1.get(i).put("userType", "02");
					}
				}
			}
		}
		Map<String, Object> param1 = new LinkedHashMap<String, Object>();
		param1.put("N", "扭动阶段正常GMs");
		param1.put("F", "不安运动阶段的正常GMs");
		param1.put("PR", "“单调性”GMs");
		param1.put("Ch", "“混乱性”GMs");
		param1.put("CS", "“痉挛-同步性”GMs");
		param1.put("AF", "“异常性”不安运动");
		param1.put("F-", "不安运动缺乏");
		paramMap.put("option", param1);
		String x = "26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22";
		String y = "N,F,PR,Ch,CS,AF,F-";
		paramMap.put("x", x);
		paramMap.put("y", y);
		paramMap.put("result", paramMap1);
		return paramMap;
	}

	//查询gms指导意见记录
	@Override
	public List<Map<String, Object>> getEvaluationGuideGms(Map<String, Object> param) throws Exception {
		List<Map<String,Object>> guideMap = followEvaluationDao.selectEvaluationGmsGuide(param);
		if(null !=guideMap && guideMap.size()>0){
			for(int i =0 ;i<guideMap.size();i++){
				if(null != guideMap.get(i).get("updateTime")){
					guideMap.get(i).put("updateTime",DateUtil.getTimeStampSec(guideMap.get(i).get("updateTime").toString()));
				}
				if(null != guideMap.get(i).get("createTime")){
					guideMap.get(i).put("createTime", DateUtil.getTimeStampSec(guideMap.get(i).get("createTime").toString()));
				}
			}
		}
		return guideMap;
	}

	//职业紧张压力指数问卷
	@Override
	public Map<String, Object> getPregnantLESPostion(Map<String, Object> paramsMap) throws Exception {
		Jedis jedis = null;
		String examinationPaperName =(String) paramsMap.get("examinationPaperName");
		JSONObject json = null;
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION);
			String json1 = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,examinationPaperName);
			if(StringUtils.isEmpty(json1)){
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("field",Constants.FOLLOW_EVALUATION_PREGNANT_KEY);
				paramMap.put("key",examinationPaperName);
				FuAssessMentPosition position = followEvaluationDao.selectAssessMentPosition(paramMap);
				if(null != position){
					json1 = position.getValue();
					jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,examinationPaperName,json1);
				}
			}
			//高危儿五项特殊处理
			if(Constants.FOLLOW_EVALUATION_PREGNANT_FHRIS.equals(examinationPaperName)) {
				//获取患者信息
				Patient patient = (Patient) paramsMap.get("patient");
				//获取当前或者的矫正年龄
				Date birthday = DateUtil.getDate_8(patient.getBirthday());
				int days = DateUtil.daysBetween(birthday, new Date());
				int month = days % 30 > 15 ? days / 30 + 1 : days / 30;
				if(patient.getPregnancyDay()<260 && month<25 && patient.getPregnancyDay()>0) {
					int day = 280 - patient.getPregnancyDay();
					days = days - day;
					month = days/30;
				}
				System.out.println(month);
				json  = JSON.parseObject(json1);
				JSONArray jsonarray = (JSONArray) json.get("quesiton");
				if(jsonarray!=null && jsonarray.size()>0) {
					for(int i=0;i<jsonarray.size();i++) {
						JSONObject jsons = jsonarray.getJSONObject(i);
						if("异常姿势检查".equals(jsons.get("name"))) {
							JSONArray jsonarray1 = (JSONArray) jsons.get("question");
							for(int j =0;j<jsonarray1.size();j++) {
								JSONObject json2 = jsonarray1.getJSONObject(j);
								String topic =  (String) json2.get("topic");
								if("手握拳".equals(topic)) {
									JSONArray jsonarray2 = (JSONArray) json2.get("option");
									for(int k =0;k<jsonarray2.size();k++) {
										JSONObject json3 = jsonarray2.getJSONObject(k);
										String name =  json3.getString("name");
										if(month>3 && "有".equals(name) ) {
											json3.put("colour", "red");
										}else if("有".equals(name)){
											json3.put("colour", "green");
										}
									}
								}else if("拥抱反射".equals(topic)) {
									JSONArray jsonarray2 = (JSONArray) json2.get("option");
									for(int k =0;k<jsonarray2.size();k++) {
										JSONObject json3 = jsonarray2.getJSONObject(k);
										String name =  json3.getString("name");
										if(month>=1 && month<=3 && "无".equals(name) ) {
											json3.put("colour", "red");
										}else if("无".equals(name)) {
											json3.put("colour", "green");
										}
									}
								}else if("握持反射".equals(topic)) {
									JSONArray jsonarray2 = (JSONArray) json2.get("option");
									for(int k =0;k<jsonarray2.size();k++) {
										JSONObject json3 = jsonarray2.getJSONObject(k);
										String name =  json3.getString("name");
										if(month<=4 && "无".equals(name) ) {
											json3.put("colour", "red");
										}else if ("无".equals(name)) {
											json3.put("colour", "green");
										}
									}
								}
							}
						}
					}
				}

			}
			Map<String, Object> postionMap =  new LinkedHashMap<String, Object>();
			if(Constants.FOLLOW_EVALUATION_PREGNANT_FHRIS.equals(examinationPaperName)) {
				postionMap = json;
			}else {
				postionMap = ToolUtils.typeCast(JSON.parse(json1));
			}
			return postionMap;
		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}


	//查询用户评估信息查询当前用户评估的记录，以每天分组
	@Override
	public List<Map<String, Object>> queryPtResultTimes(Map<String, Object> param) throws Exception {
		List<Map<String,Object>> guideMap = followEvaluationDao.selectEvaluationResultGroup(param);
		return guideMap;
	}

	//查询gms指导意见记录
	@Override
	public List<Map<String, Object>> queryPtResultDay(Map<String, Object> param) throws Exception {
		List<Map<String,Object>> guideMap = followEvaluationDao.selectEvaluationResultGroupType(param);
		return guideMap;
	}


	//gesell指导意见
	@Override
	public Map<String, Object> getGesellGuide(Map<String, Object> param, Patient pt) throws Exception {
		Jedis jedis = null;
		String keys = Constants.FOLLOW_EVALUATION_GESELL_GUIDE;
		//纠正胎龄不足280天，月龄 = 当前日期 - 预产期， 预产期 = 出生日期 +（280 - 纠正胎龄）;
		Date birthday = DateUtil.getDate_8(pt.getBirthday());
		int days = 0;
		if(StringUtils.isEmpty(param.get("createTime"))) {
			days = DateUtil.daysBetween(birthday, new Date());
		}else {
			days = DateUtil.daysBetween(birthday,  DateUtil.getDate_8((String)param.get("createTime")));
		}
		int month = days % 30 > 15 ? days / 30 + 1 : days / 30;
		if(pt.getPregnancyDay()<260 && month<25 && pt.getPregnancyDay()>0) {
			int day = 280 - pt.getPregnancyDay();
			birthday = DateUtil.addDay(birthday, day);
			if(StringUtils.isEmpty(param.get("createTime"))) {
				days = DateUtil.daysBetween(birthday, new Date());
			}else {
				days = DateUtil.daysBetween(birthday,  DateUtil.getDate_8((String)param.get("createTime")));
			}
			month = days % 30 > 15 ? days / 30 + 1 : days / 30;
		}
		//获取指导意见
		try {
			// 大运动
			float sportsPostion = 0;
			// 精细动作
			float fineActionPostion = 0;
			// 适应性
			float adaptabilityPostion = 0;
			// 语言
			float languagePostion = 0;
			// 个人——社会
			float personalPostion = 0;
			//通过评估id查询用户评估信息
			PtEvaluationResult pr = followEvaluationDao.selectEvaluationResult(param);
			if(pr!=null) {
				String score = pr.getScore();
				JSONObject jsons = JSONObject.parseObject(score);
				if(jsons!=null) {
					//获取到用户评估能区DQ
					for(int i=0;i<jsons.size();i++) {
						sportsPostion = jsons.getJSONObject("sportsPostion").getFloat("DQ");
						fineActionPostion = jsons.getJSONObject("fineActionPostion").getFloat("DQ");
						adaptabilityPostion = jsons.getJSONObject("adaptabilityPostion").getFloat("DQ");
						languagePostion = jsons.getJSONObject("languagePostion").getFloat("DQ");
						personalPostion = jsons.getJSONObject("personalPostion").getFloat("DQ");
					}
				}
			}

			Map<String,Float> map = new TreeMap<String,Float>();
			map.put("sportsPostion", sportsPostion);
			map.put("fineActionPostion", fineActionPostion);
			map.put("adaptabilityPostion", adaptabilityPostion);
			map.put("languagePostion", languagePostion);
			map.put("personalPostion", personalPostion);
			//这里将map.entrySet()转换成list
			List<Map.Entry<String,Float>> list = new ArrayList<Map.Entry<String,Float>>(map.entrySet());
		    //然后通过比较器来实现排序
		    Collections.sort(list,new Comparator<Map.Entry<String,Float>>() {
		      //升序排序
		      public int compare(Entry<String,Float> o1,
		          Entry<String,Float> o2) {
		        return o1.getValue().compareTo(o2.getValue());
		      }

		    });

			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION);
			String difficultStr = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,keys+"_01");
			String simpleStr = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,keys+"_02");

			if(StringUtils.isEmpty(difficultStr) || StringUtils.isEmpty(simpleStr)){
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("field",Constants.FOLLOW_EVALUATION_PREGNANT_KEY);
				paramMap.put("key",keys+"_02");
				FuAssessMentPosition simplePosition = followEvaluationDao.selectAssessMentPosition(paramMap);
				paramMap.put("key",keys+"_01");
				FuAssessMentPosition difficultPosition = followEvaluationDao.selectAssessMentPosition(paramMap);
				if(null != simplePosition){
					simpleStr = simplePosition.getValue();
					jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,keys+"_02",simpleStr);
				}
				if(null != difficultPosition){
					difficultStr = difficultPosition.getValue();
					jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,keys+"_01",difficultStr);
				}
			}

			Map<String,Object> postionMap = new LinkedHashMap<String,Object>();
			net.sf.json.JSONObject simple = net.sf.json.JSONObject.fromObject(simpleStr);
			net.sf.json.JSONObject difficult = net.sf.json.JSONObject.fromObject(difficultStr);

			String Month = switchMonth(month);
			 //需要判断是否需要复杂版训练计划
			int  num = 1;
		    for(Entry<String, Float> mapping:list){
		    	map.put(mapping.getKey(),mapping.getValue());
		    	if("sportsPostion".equals(mapping.getKey())) {
		    		if(mapping.getValue()<75){
		    			postionMap.put(ToolUtils.toChineseStr(num)+"、大运动", difficult.getJSONObject(Month).get("sportsPostion"));
		    		}else{
		    			postionMap.put(ToolUtils.toChineseStr(num)+"、大运动", simple.getJSONObject(Month).get("sportsPostion"));
		    		}
		    	}else if("fineActionPostion".equals(mapping.getKey())) {
		    		if(mapping.getValue()<75){
		    			postionMap.put(ToolUtils.toChineseStr(num)+"、精细动作", difficult.getJSONObject(Month).get("fineActionPostion"));
		    		}else{
		    			postionMap.put(ToolUtils.toChineseStr(num)+"、精细动作", simple.getJSONObject(Month).get("fineActionPostion"));
		    		}
		    	}else if("adaptabilityPostion".equals(mapping.getKey())) {
		    		if(mapping.getValue()<75){
		    			postionMap.put(ToolUtils.toChineseStr(num)+"、适应能力", difficult.getJSONObject(Month).get("adaptabilityPostion"));
		    		}else{
		    			postionMap.put(ToolUtils.toChineseStr(num)+"、适应能力", simple.getJSONObject(Month).get("adaptabilityPostion"));
		    		}
		    	}else if("languagePostion".equals(mapping.getKey())) {
		    		if(mapping.getValue()<75){
		    			postionMap.put(ToolUtils.toChineseStr(num)+"、语言能力", difficult.getJSONObject(Month).get("languagePostion"));
		    		}else{
		    			postionMap.put(ToolUtils.toChineseStr(num)+"、语言能力", simple.getJSONObject(Month).get("languagePostion"));
		    		}
		    	}else if("personalPostion".equals(mapping.getKey())) {
		    		if(mapping.getValue()<75){
		    			postionMap.put(ToolUtils.toChineseStr(num)+"、社交行为能力", difficult.getJSONObject(Month).get("personalPostion"));
		    		}else{
		    			postionMap.put(ToolUtils.toChineseStr(num)+"、社交行为能力", simple.getJSONObject(Month).get("personalPostion"));
		    		}
		    	}
		    	num++;
		     }

		    return postionMap;
		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}

	//解析日期
	public static String switchMonth(float month) {
		String Month="";
		if(month<2) {
			Month = "29-60";
		}else if(month>=2 && month<3){
			Month = "2";
		}else if(month>=3 && month<4){
			Month = "3";
		}else if(month>=4 && month<5){
			Month = "4";
		}else if(month>=5 && month<6){
			Month = "5";
		}else if(month>=6 && month<7){
			Month = "6";
		}else if(month>=7 && month<9){
			Month = "7-8";
		}else if(month>=9 && month<11){
			Month = "9-10";
		}else if(month>=11 && month<13){
			Month = "11-12";
		}else if(month>=13 && month<16){
			Month = "13-15";
		}else if(month>=16 && month<19){
			Month = "16-18";
		}else if(month>=19 && month<22){
			Month = "19-21";
		}else if(month>=22 && month<25){
			Month = "22-24";
		}
		return Month;
	}


	//获取gesell评估信息
	@Override
	public Map<String, Object> selectGesellScore(Map<String, Object> map) throws Exception {
		logger.info("map = "+map.toString());
		PtEvaluationResult  paramMap = followEvaluationDao.selectEvaluationResultBytime(map);
		Map<String,Object> mapOut = new LinkedHashMap<String,Object>();
		if(paramMap!=null) {
			String Score = paramMap.getScore();
			mapOut = JSONObject.parseObject(Score);
		}
		return mapOut;
	}


	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> getDSTPostion(
			Map<String, Object> paramsMap) throws Exception {
		Jedis jedis = null;
		String key = Constants.FOLLOW_EVALUATION_DST;
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION);
			String json = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,key);

			if(StringUtils.isEmpty(json)){
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("field",Constants.FOLLOW_EVALUATION_PREGNANT_KEY);
				paramMap.put("key",key);
				FuAssessMentPosition position = followEvaluationDao.selectAssessMentPosition(paramMap);
				if(null != position){
					json = position.getValue();
					jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,key,json);
				}
			}

			Map<String, Object> postionMap = JSON.parseObject(json,LinkedHashMap.class,Feature.OrderedField);
			return postionMap;

		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}

	@Override
	@Transactional
	public int saveEltDstRecoreResults(EltDstRecored dst) throws Exception {
		String queueId = dst.getQueueId();
		String userId = dst.getUserId();
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("queueId", queueId);
		map.put("userId", userId);
		List<PatientQueueScheme> list = iPatientQueueSchemeDao.selectByUserId(map);
		String ptSchemeid = "";
		if(list!=null && list.size()>0) {
			ptSchemeid= list.get(0).getId();
		}
		dst.setPtSchemeid(ptSchemeid);
		int i = iEltDstRecoreDAO.saveEltDstRecoreResults(dst);
		return i;
	}

	@Override
	public Map<String,Object> selectPtDSTResults(Map<String, Object> map) throws Exception {
		Map<String,Object> mapOut = new HashMap<String,Object>();
		int page = (map.get("page") != null && !StringUtils
				.isEmpty(map.get("page").toString())) ? Integer.parseInt(map.get("page").toString()) : 1;
		int rows = (map.get("rows") != null && !StringUtils
				.isEmpty(map.get("rows").toString())) ? Integer.parseInt(map.get("rows").toString()) : 20;

		String sourseType= (String)map.get("sourseType");
		if(Constants.SOURCE_TYPE_APP.equals(sourseType)){

		}else{
			map.put("start", rows * (page - 1));
			map.put("end", rows);
		}
		int total=0;
		// paramMap.put("status","01");
		List<EltDstRecored> list = iEltDstRecoreDAO.selectEltDstRecoreById(map);
		if(list!=null&&list.size()>0) {
			total = iEltDstRecoreDAO.selectEltDstRecoreByIdtotal(map);
		}
		mapOut.put("rows", list);
		mapOut.put("total", total);

		return mapOut;
	}


	/**
	 * 获取gesell评估每天的最新一条记录
	 *
	 **/
	@Override
	public List<Map<String, Object>> selectGesellScoreList(Map<String, Object> map) throws Exception {
		logger.info("map = "+map.toString());
		List<Map<String,Object>> list = followEvaluationDao.selectEvaluationGroupByDate(map);
		return list;
	}

	/**
	 * 删除患者的评估历史记录（物理）。
	 * @param evaluationId
	 * @return 是否成功删除了记录。
	 * @throws Exception
	 */
	@Override
	public Boolean deleteEvaluationHistory(final String evaluationId) throws Exception {
		//删除1条pt_evaluation_result表的记录。
		int delEvaResultRows= followEvaluationDao.deleteEvaluationResult(evaluationId);
		logger.info("++++deleteEvaluationHistory() delEvaResultRows:"+delEvaResultRows);
		//删除若干条pt_evaluation_guide表的记录。
		int delEvaGuideRows	= followEvaluationDao.deleteEvaluationGuide(evaluationId);
		logger.info("++++deleteEvaluationHistory() delEvaGuideRows:"+delEvaGuideRows);
		if (1 == delEvaResultRows)	{
			return true;
		} else {
			logger.error("----deleteEvaluationHistory() FAIL to 删除1条pt_evaluation_result表的记录!!");
			return false;
		}
	}

	@Override
	@Transactional
	public int saveDraftForPeabody(PtEvaluationResult draft) throws Exception {
		final String patId	= draft.getUserId();
		logger.info("++++saveDraftForPeabody() patId:"+patId+", draftId:"+draft.getId()+", begin to delete.");
		int delRet	= followEvaluationDao.deleteDraftForPeabody(patId);
		logger.info("++++saveDraftForPeabody() delRet:"+delRet+", begin to insert.");
		int insRet	= followEvaluationDao.saveDraftForPeabody(draft);
		logger.info("++++saveDraftForPeabody() insRet:"+insRet);
		return insRet;
	}
	@Override
	public int deleteDraftForPeabody(final String patId) throws Exception {
		return followEvaluationDao.deleteDraftForPeabody(patId);
	}
	@Override
	public List<PtEvaluationResult> selectDraftForPeabody(Map<String, Object> paraMap) throws Exception {
		return followEvaluationDao.selectDraftForPeabody(paraMap);
	}

}
